角度材料md-error ng如果不起作用

时间:2017-09-15 15:42:45

标签: angular angular-material angular-forms

我正在尝试使用角度材料验证密码,但在<md-error>中包含<md-form-field>标记时,它无效。你可以看到它在哪里工作,哪里不工作。我做错了什么?

  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() {
      }

  }

1 个答案:

答案 0 :(得分: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");

}