Angular2:如何访问 Component.ts 中的表单验证字段
Angular2: How to access to form validation fields in Component.ts
例如我有一个表单(不包含 FormGroup)并且视图看起来像这样
<form #f="ngForm" novalidate>
<label>Email</label>
<input type="email" [(ngModel)]="player.email" class="form-control" name="email" #email="ngModel" required>
<!-- with #email code, now, in view, I have variable with name email!!! -->
</form>
使用#email 标记,我声明了一个名称为'email' 的变量,使用这个变量我可以检查验证错误。例如
<div [hidden]="email.valid || email.pristine"
class="alert alert-danger">
email is required
</div>
如何在我的组件 class 中访问这个变量?
您必须通过在组件中如下声明 ViewChild 来使用它:
export class MyCompoment {
@ViewChild('email') email: ngModel;
ngOnInit(){
console.log(this.email);
}
}
例如我有一个表单(不包含 FormGroup)并且视图看起来像这样
<form #f="ngForm" novalidate>
<label>Email</label>
<input type="email" [(ngModel)]="player.email" class="form-control" name="email" #email="ngModel" required>
<!-- with #email code, now, in view, I have variable with name email!!! -->
</form>
使用#email 标记,我声明了一个名称为'email' 的变量,使用这个变量我可以检查验证错误。例如
<div [hidden]="email.valid || email.pristine"
class="alert alert-danger">
email is required
</div>
如何在我的组件 class 中访问这个变量?
您必须通过在组件中如下声明 ViewChild 来使用它:
export class MyCompoment {
@ViewChild('email') email: ngModel;
ngOnInit(){
console.log(this.email);
}
}