Angular Forms

编程入门 行业动态 更新时间:2024-10-08 00:35:23
Angular Forms - 什么是正确的初始化方式(Angular Forms - What is the correct way to initialize)

我有一个基本的形式,我已经建立了3个领域。 名称,描述和ID。 数据意味着由一个服务填充,该服务调用一个返回JSON的C#API,然后将其加载到表单中。

当它打开时,我得到正确的数据,但我得到这个错误。 如果我删除名称输入,则错误只会移至说明字段,然后是标识。

我仍然在学习Angular,但已经读了一堆来尝试解决这个问题。 我想我已经得到了它的所有权利,但我猜这是初始化的问题,因为如果我在从场景服务获取数据之前添加此代码,错误就会消失。

this.scenario = { 'id': 0, 'name': '', 'description': '', 'dateCreated': '', 'createdBy': '', 'dateModified': '', 'modifiedBy': '', 'active': true };

那么对此进行编码的正确方法是什么,这样我的界面就不需要硬编码就可以初始化了?

test.component.html

<h1> Edit Scenario - {{ name.value }} </h1> <div class='panel-body'> <form novalidate #scenarioForm="ngForm" (ngSubmit)="saveForm()"> <div class='row'> <div class='col-md-1'><label for="scenarioName" class="control-label">Name</label></div> <div class='col-md-6'> <div class="form-group" [class.has-error]="name.invalid && name.touched"> <input class="form-control" #name="ngModel" name="scenarioName" type="text" maxlength="50" placeholder="Scenario name" required [(ngModel)]="scenario.name"> </div> </div> </div> <div class='row'> <div class='col-md-1'><label for="descption">Descption</label></div> <div class='col-md-6'> <div class="form-group" [class.has-error]="description.invalid && description.touched"> <textarea #description="ngModel" ngControl="description" class="form-control" rows="4" maxlength="500" placeholder="What is this scenario for?" required name="description" [(ngModel)]="scenario.description"></textarea> <div *ngIf="description.invalid && description.dirty" class="alert alert-danger"> Description is required, and must be at least blah blah... </div> </div> </div> </div> <div class='panel-footer'> <button class="btn btn-default" type="submit">Save</button> </div> <br><br> <input #id type="text" name="id" [(ngModel)]="scenario.id" #id="ngModel"> </form> <div id="debugging"> <br> Valid? {{scenarioForm.valid}}<br> Model: {{ scenario | json }} <br> Model: {{ result | json }}<br> Form: {{ scenarioForm.value | json }} <br> </div>

test.component.ts

import { Component, OnInit, NgModule } from '@angular/core'; import { SharedModule } from './../shared/shared.module'; import { FormsModule, NgForm, FormGroup } from '@angular/forms'; import { CommonModule } from '@angular/common'; import { ScenarioService } from './scenario.service'; import { IScenario } from './scenario'; import { Router, ActivatedRoute } from '@angular/router'; @NgModule({ imports: [ FormsModule ], exports: [FormsModule] }) @Component({ selector: 'app-scenario-form', templateUrl: './test.component.html', }) export class TestComponent implements OnInit { // tslint:disable-next-line:no-inferrable-types private pageTitle: string = 'New Scenario'; scenario: IScenario; result: IScenario; constructor(private _scenarioService: ScenarioService, private _route: ActivatedRoute) {} ngOnInit() { const scenarioId = this._route.snapshot.paramMap.get('id'); if (scenarioId) { this._scenarioService.getScenario(+scenarioId).subscribe( scenario => this.scenario = scenario); } } }

I have a basic form that I have built with 3 fields. Name, description and id. The data is meant to be populated by a service that calls out to a C# API that returns JSON that is then loaded to the form.

When it opens I get the correct data but I get this error. If I striped out the name input, the errors just move to the description field then the id.

I am still learning Angular, but have read a heap to try and fix this. I think I've got it all right, but I'm guessing it's something to do with initialisation because if I add this code before getting the data from the scenario service, the errors go.

this.scenario = { 'id': 0, 'name': '', 'description': '', 'dateCreated': '', 'createdBy': '', 'dateModified': '', 'modifiedBy': '', 'active': true };

So what is the correct way to code this so my interface is initialised without having to hard code it?

test.component.html

<h1> Edit Scenario - {{ name.value }} </h1> <div class='panel-body'> <form novalidate #scenarioForm="ngForm" (ngSubmit)="saveForm()"> <div class='row'> <div class='col-md-1'><label for="scenarioName" class="control-label">Name</label></div> <div class='col-md-6'> <div class="form-group" [class.has-error]="name.invalid && name.touched"> <input class="form-control" #name="ngModel" name="scenarioName" type="text" maxlength="50" placeholder="Scenario name" required [(ngModel)]="scenario.name"> </div> </div> </div> <div class='row'> <div class='col-md-1'><label for="descption">Descption</label></div> <div class='col-md-6'> <div class="form-group" [class.has-error]="description.invalid && description.touched"> <textarea #description="ngModel" ngControl="description" class="form-control" rows="4" maxlength="500" placeholder="What is this scenario for?" required name="description" [(ngModel)]="scenario.description"></textarea> <div *ngIf="description.invalid && description.dirty" class="alert alert-danger"> Description is required, and must be at least blah blah... </div> </div> </div> </div> <div class='panel-footer'> <button class="btn btn-default" type="submit">Save</button> </div> <br><br> <input #id type="text" name="id" [(ngModel)]="scenario.id" #id="ngModel"> </form> <div id="debugging"> <br> Valid? {{scenarioForm.valid}}<br> Model: {{ scenario | json }} <br> Model: {{ result | json }}<br> Form: {{ scenarioForm.value | json }} <br> </div>

test.component.ts

import { Component, OnInit, NgModule } from '@angular/core'; import { SharedModule } from './../shared/shared.module'; import { FormsModule, NgForm, FormGroup } from '@angular/forms'; import { CommonModule } from '@angular/common'; import { ScenarioService } from './scenario.service'; import { IScenario } from './scenario'; import { Router, ActivatedRoute } from '@angular/router'; @NgModule({ imports: [ FormsModule ], exports: [FormsModule] }) @Component({ selector: 'app-scenario-form', templateUrl: './test.component.html', }) export class TestComponent implements OnInit { // tslint:disable-next-line:no-inferrable-types private pageTitle: string = 'New Scenario'; scenario: IScenario; result: IScenario; constructor(private _scenarioService: ScenarioService, private _route: ActivatedRoute) {} ngOnInit() { const scenarioId = this._route.snapshot.paramMap.get('id'); if (scenarioId) { this._scenarioService.getScenario(+scenarioId).subscribe( scenario => this.scenario = scenario); } } }

最满意答案

由于您是通过异步方式获取API的响应,因此您需要首先处理空值,您可以使用安全的导航运算符来执行此操作

<input #id type="text" name="id" [(ngModel)]="scenario?.id" #id="ngModel">

同样适用于你所有的领域。

如上所述,其他方法是通过初始化对象Scenario来修复

由于您需要完成双向数据绑定,因此需要通过创建实例来初始化对象

scenario: IScenarioUpdate = {modifiedBy: ''}

Since you are getting the response from API asynchronously, you need to handle the null initially, you can do that with safe navigation operator

<input #id type="text" name="id" [(ngModel)]="scenario?.id" #id="ngModel">

same applies for all your fields.

As you mentioned above, other way is to fix via initializing the object Scenario

Since you need to accomplish two way data binding, you need to initialize the object by creating an instance

scenario: IScenarioUpdate = {modifiedBy: ''}

更多推荐

本文发布于:2023-08-04 21:26:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1422313.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Angular   Forms

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!