如何验证表格?

时间:2019-06-22 23:45:18

标签: angular typescript

我在验证尝试过的多种表单时遇到问题,但无法获得解决方案,请问能否解决?

import { Component, AfterViewInit, ElementRef, ViewChild } from '@angular/core';
import panzoom from "panzoom";

@Component({
  selector: 'hello',
  template: `<img id="scene" #scene src="https://www.probytes.net/wp-content/uploads/2018/01/5-1.png">`,
  styles: []
})
export class HelloComponent implements AfterViewInit {
  @ViewChild('scene', { static: false }) scene: ElementRef;

  ngAfterViewInit() {
    // panzoom(document.querySelector('#scene'));
    panzoom(this.scene.nativeElement);
  }
}

这是我的代码

<div *ngIf="firstname.error?.required">First Name is required</div> 

这是我尝试使用

时收到的错误
<div class="md-form">
                  <input type="text" id="materialRegisterFormFirstName" class="form-control"  name="materialRegisterFormFirstName" [(ngModel)]="firstname">
                  <label for="materialRegisterFormFirstName">First name</label>
                  <div *ngIf="firstname.error?.required">First Name is required</div>
                </div>

1 个答案:

答案 0 :(得分:0)

似乎您使用的是模板驱动表单,该表单主要使用NgModel

有了这一点,您需要:

 <input type="text" 
        id="materialRegisterFormFirstName" 
        class="form-control"  
        name="firstname"              // It should have the same name as your ngModel
        [(ngModel)]="firstname"
        #firstname="ngModel">         // You need to add this input reference

 // You can then perform this line since the "firstname" refers to the #firstname="ngModel" from the input property:
 <div *ngIf="firstname.error?.required">First Name is required</div>