我有简单的表格
<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
您错过了onInit实现,
首先添加InputOverviewExample implements OnInit
以正确实现和使用该ngOnInit
功能。
其次,由于Reactive表单是sync表单,因此console.log
在获取表单initialized
之前和form control
添加表单之前运行。
另外,表单控制的一般实现使用form builder
in构造函数,因为您尚未意识到这一点,因此您已经遇到了这一问题,因此以下代码将为您解决
import { Component, ViewChild, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
/**
* @title Basic Inputs
*/
@Component({
selector: 'input-overview-example',
styleUrls: ['input-overview-example.css'],
templateUrl: 'input-overview-example.html',
})
export class InputOverviewExample implements OnInit {
comment = null;
@ViewChild('f')
form: NgForm
ngOnInit() {
setTimeout(() => {
console.log(this.form.controls);
console.log(typeof this.form.controls);
console.log(Object.keys(this.form.controls));
console.log(this.form.controls.myname);
console.log(this.form.controls['myname']);
})
}
}
附:
对于您的问题,模板驱动的表单可以在后台的可响应表单API上运行吗?,答案是肯定的
这里是解释:
NgModel伪指令创建FormControl实例以管理模板表单控件,并且name属性告诉NgModel伪指令将哪个FormControl存储在父FormGroup中的密钥
<input name="foo" ngModel>
等于:
let model = new FormGroup({
"foo": new FormControl()
});
您面临的主要问题是控制台行为,
Console
首先执行,然后再分配值,因此在控制台执行后分配值时,将无法访问任何方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句