角度表单 - 初始化的正确方法是什么

时间:2018-05-14 01:12:58

标签: javascript angular angular-forms

我有一个用3个字段构建的基本表单。姓名,描述和身份证明。这些数据应由一个服务填充,该服务调用C#API,返回JSON,然后将其加载到表单中。

当它打开时,我得到了正确的数据,但是我收到了这个错误。如果我将名称输入条带化,则错误只会移至描述字段,然后是id。

enter image description here

我还在学习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);
    }
  }
}

1 个答案:

答案 0 :(得分:1)

由于您是异步获取API的响应,因此最初需要处理null,您可以使用安全导航操作符

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

同样适用于您的所有字段。

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

由于您需要完成双向数据绑定,因此需要通过创建实例

来初始化对象
scenario: IScenarioUpdate = {modifiedBy: ''}
相关问题