为什么我不能从NgForm获取表单控件 [英] Why I cannot get form control from NgForm

查看:112
本文介绍了为什么我不能从NgForm获取表单控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表格很简单

<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是

以下是说明:

NgModel指令创建FormControl实例来管理 模板表单控件和name属性告诉NgModel 指令将哪个FormControl存储在父项下的键 表格组

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,然后将值分配给它,因此 赋值时将无法访问任何方法 在执行控制台之后.

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.

这是@yurzui提供的一个很好的例子

这篇关于为什么我不能从NgForm获取表单控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆