2017-09-15 94 views
0

我試圖用角度材料驗證密碼,但當標籤<md-error>包含在<md-form-field>中時它不起作用。你可以看到它在哪裏工作,哪裏不工作。我做錯了什麼?角度材料md錯誤ng如果不起作用

import { Component, OnInit } from '@angular/core'; 
    import 'rxjs/add/operator/map'; 
    import { 
     AbstractControl, 
     FormControl, 
     Validators, 
     FormGroup, 
     FormBuilder, 
     FormsModule, 
     FormGroupDirective, 
     NgForm 
    } from '@angular/forms'; 

    function passwordMatcher(c: AbstractControl) { 
     if (!c.get('password') || !c.get('confirm')) return null; 
     return c.get('password').value === c.get('confirm').value ? null 
    : {'nomatch': true}; 
    } 

    @Component({ 
    selector: 'app-testing', 
    template: ` 

     <form [formGroup]="form"> 
      <div formGroupName="account"> 
       <md-form-field> 
        <input mdInput 
          formControlName="password"> 
       </md-form-field> 
       <md-form-field> 
        <input mdInput 
          formControlName="confirm"> 
        <md-error 
    *ngIf="form.hasError('nomatch','account')"> 
         THIS DOESN'T WORK 
        </md-error> 
       </md-form-field> 
      </div> 
     </form> 

     <md-error *ngIf="form.hasError('nomatch','account')"> 
      THIS WORK 
     </md-error> 

     <p>{{form.value | json}}</p> 
     <p>{{form.status}}</p> 
     <p>{{form.get('account.confirm').status}}</p> 
     {{form.hasError('nomatch', 'account')}} 
    `, 
    styleUrls: ['./testing.component.css'] 
    }) 
    export class TestingComponent implements OnInit { 

     form: FormGroup; 

     constructor(public fb: FormBuilder) { 
      this.form = this.fb.group({ 
       account: this.fb.group({ 
        password: '', 
        confirm: '' 
       }, {validator: passwordMatcher}) 
      }); 
     } 

     ngOnInit() { 
     } 

    } 

回答

0
try to add the following code 
<md-form-field> 
       <input mdInput 
         formControlName="confirm" [errorStateMatcher]="myErrorStateMatcher.bind(this)"> 
       <md-error 
*ngIf="form.hasError('nomatch','account')"> 
        THIS DOESN'T WORK 
       </md-error> 
      </md-form-field> 
在組件

添加功能

myErrorStateMatcher(){ 

    return this.form.controls["account"].getError("nomatch"); 

}