问题描述
我的表格很简单
<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']);
}
}
问题是,控制台输出是:
The thing is, console output is:
{}
myname: Object { pristine: true, touched: false, status: "INVALID", … }
Array []
undefined
所以为什么我不能按名称访问表单控件,以及为什么Object.keys
返回空数组,而控制台却说form.controls
中有一些键呢?这是一个游乐场,所以请忽略重复的表格输入等. https://stackblitz.com/edit/angular-urqles
So why I cannot access form controls by name, and why Object.keys
returns empty array while console says there are some keys in form.controls
??This is a playground so please ignore duplicated form inputs etc.https://stackblitz.com/edit/angular-urqles
推荐答案
您错过了onInit实现,
You missed the onInit implementation,
首先添加InputOverviewExample implements OnInit
以正确实现和使用ngOnInit
函数.
First add InputOverviewExample implements OnInit
to correctly implement and use the ngOnInit
function.
第二,由于反应性表单是同步的,因此console.log
在表单获取initialized
之前和添加form control
之前运行.
Second, Since the Reactive forms are synchronous, the console.log
runs before the form gets initialized
and before the form control
gets added.
此外,表单控件的通用实现在构造函数中使用form builder
,因为您尚未意识到这一点,因此您已经遇到了这个问题,因此以下代码将为您解决
Also, the general implementation of form control uses the form builder
in constructor, since you havent taken that, you had faced this, so the below code will solve it for you
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']);
})
}
}
Ps:
对于您的问题那么模板驱动的表单可以在幕后的反应式API上工作吗?, ANSWER是
以下是说明:
<input name="foo" ngModel>
等效于:
let model = new FormGroup({
"foo": new FormControl()
});
您遇到的主要问题是控制台行为,
这篇关于为什么我不能从NgForm获取表单控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!