角2 - 获取到formGroup

问题描述:

参考在角2种模板驱动的形式,我可以写角2 - 获取到formGroup

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

您可以使用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. 
    } 
} 
+0

我曾试图做像你说的,但也使用阅读:ViewContainerRef。那是错误的。忽略读取选项会产生一个NgForm,这是我想要的对象的实际类型,而不是我认为的FormGroup。 我通过看这个答案了解了这一点:http://*.com/questions/36583078/how-to-get-reference-to-angular-built-controlgroup-from-within-a-component?rq=1 – Etchelon