gpt4 book ai didi

angular - 为什么我无法从 NgForm 获得表单控制

转载 作者:行者123 更新时间:2023-12-03 23:16:11 25 4
gpt4 key购买 nike

我有简单的形式

<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功能。

二、自 react 形式是同步的 , console.log在表单获取之前运行 initialized和之前 form control被添加。

另外,一般实现 表单控件使用 form builder在构造函数中,既然你没有接受,你就遇到了这个,所以下面的代码会为你解决

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']);
})

}
}

Here is the DEMO of the working code

ps:

对于您的问题,那么模板驱动的表单是否可以在后台处理响应式表单 API?, 答案是肯定的

这是解释:

The NgModel directive creates the FormControl instance to manage the template form control and the name attribute tells the NgModel directive what key to store that FormControl under in the parent FormGroup


<input name="foo" ngModel>

相当于:
let model = new FormGroup({
"foo": new FormControl()
});

您的主要问题是控制台行为,

Console executed first and later the value is assigned to it, so will not get access to any of the methods when value gets assigned after the execution of console.



Here is a nice example given by @yurzui

关于angular - 为什么我无法从 NgForm 获得表单控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50267808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com