【问题标题】:Angular2: How to access to form validation fields in Component.ts [duplicate]Angular2:如何访问 Component.ts [重复] 中的表单验证字段
【发布时间】:2017-04-21 09:50:53
【问题描述】:

例如,我有一个表单(不是 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>

如何在我的组件类中访问这个变量?

【问题讨论】:

  • 几乎一样,但确实有帮助。对我来说很好的解决方案,谢谢!

标签: validation angular angular2-forms


【解决方案1】:

您必须通过在组件中如下声明 ViewChild 来使用它:

export class MyCompoment {
  @ViewChild('email') email: ngModel;

  ngOnInit(){
    console.log(this.email);
  }
}

【讨论】:

    猜你喜欢
    • 2021-02-23
    • 2017-04-15
    • 1970-01-01
    • 2017-10-27
    • 2016-11-07
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    相关资源
    最近更新 更多