为什么我无法从NgForm获得表单控件

时间:2018-05-10 07:30:11

标签: angular

我有简单的表格

<form novalidate #f="ngForm">
  <mat-form-field class="example-full-width">
    <input matInput placeholder="Favorite food" name="myname" required [(ngModel)]="comment">
    <mat-error>Is required lol</mat-error>
  </mat-form-field>

  <mat-form-field class="example-full-width">
    <input matInput placeholder="Favorite food" required name="some">
  </mat-form-field>
</form>

和组件为

export class InputOverviewExample {
  comment = null;
  @ViewChild('f')
  form: NgForm


  ngOnInit() {
    console.log(this.form.controls);
    console.log(Object.keys(this.form.controls));

    console.log(this.form.controls.myname);
    console.log(this.form.controls['myname']);
  }
}

问题是,控制台输出是:

{}
​
    myname: Object { pristine: true, touched: false, status: "INVALID", … }
        Array []
        undefined

那么为什么我不能按名称访问表单控件,为什么Object.keys返回空数组,而控制台说form.controls中有一些键? 这是一个游乐场所以请忽略重复的表格输入等。 https://stackblitz.com/edit/angular-urqles

0 个答案:

没有答案