【问题标题】:Angular 2 - get a reference to the formGroupAngular 2 - 获取对 formGroup 的引用
【发布时间】:2017-04-15 02:30:20
【问题描述】:

在 Angular 2 模板驱动的表单中,我可以编写

<form #form="ngForm">
[...]
</form>

ngForm 是一个 FormGroup,据我所知。如何在相应的组件中抓取该对象?

class FormComponent {
    formGroup: FormGroup;    // How do I have the form INJECTED AUTOMATICALLY by the framework? Something like a ViewChild, but it's not a view
}

一定要简单,但是文档只展示了如何使用模板中的表格。

谢谢

编辑:我要抓取的类型是 NgForm,而不是 FormGroup!

【问题讨论】:

    标签: forms angular angular2-forms


    【解决方案1】:

    您可以使用 ViewChild 装饰器从组件访问任何模板变量。在你的情况下:

    class FormComponent {
        @ViewChild('form') formGroup;
        ngOnInit() {
            this.formGroup.statusChanges().subscribe(() => {
                // Your code here!
            });
            console.log(this.formGroup); // Inspect the object for other available property and methods.
        }
    }
    

    【讨论】:

    • 我曾尝试像你说的那样做,但也使用了阅读:ViewContainerRef。那是错误的。省略 read 选项会产生一个 NgForm,这是我想要的对象的实际类型,而不是我认为的 FormGroup。通过查看这个答案,我明白了这一点:stackoverflow.com/questions/36583078/…
    猜你喜欢
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 2017-07-01
    • 2017-08-12
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多