问题描述
我想在Angular 2中使用模板驱动的表单,并且需要在我的指令中访问当前的ngForm,作为本地属性,并且我不想将它们作为参数传递.
I want to use template driven forms in Angular 2 and I need to access the current ngForm in my directive, as local property and I don't want to pass them as parameter.
我的表单如下:
<form #frm="ngForm" (ngSubmit)="save(frm)">
<input [(ngModel)]="user.name" #name="ngForm" type="text">
<a (click)="showFrm()" class="btn btn-default">Show Frm</a>
</form>
以及在我的组件中
@Component({
selector: 'addUser',
templateUrl: `Templates/AddUser`,
})
export class AddUserComponent implements CanDeactivate {
public user: User;
// how can I use this without defining the whole form
// in my component I only want to use ngModel
public frm : ngForm | ControlGroup;
public showFrm() : void{
//logs undefined on the console
console.log(this.frm);
}
}
这是可能的,因为我需要检查myFrm ist的有效性或是否在无法将当前形式作为参数传递的函数中被触摸,例如"routerCanDeactivate",我不想过多地使用模型驱动的形式来编写代码,而且我喜欢老式的ng1模型绑定.
Is this possible, because I need to check if the myFrm ist valide or was touched in a function where I can't pass the current form as parameter e.g. "routerCanDeactivate" and I don't want to use model driven forms its way too much to write in code and I love the old school ng1 model binding.
我已经更新了示例,组件中的frm未知.
I've updated my Example and the frm is not known in the component.
推荐答案
您需要在要检查的输入上使用ngControl
属性.
You need the ngControl
attribute on the inputs you want to check.
<form #frm="ngForm" (ngSubmit)="save(frm)">
<input [(ngModel)]="user.name" #name="ngForm" ngControl="name" type="text">
<a (click)="showFrm()">Show Frm</a>
</form>
,并且在组件中,您可以使用
and in the component you can access the "frm" variable with
import {Component, ViewChild} from 'angular2/core';
...
@ViewChild('frm') public userFrm: NgForm;
...
public showFrm(): void{
console.log(this.frm);
}
您无法在构造函数中访问frm
,目前尚不存在,但可以在ngAfterViewInit中访问它.
You can't access the frm
in the constructor, it's not there at this moment, but in the ngAfterViewInit you can access it.
自Angular 8以来,他们已经更新了ViewChild的参数.目前,我需要使用以下语法:
since Angular 8 or so they have updated the parameters for ViewChild. Currently I need to use this syntax:
@ViewChild('frm', { static: true })userFrm: NgForm;
这篇关于组件中的Angular 2模板驱动表单访问ngForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!