1

내 Angular 2 및 재질 응용 프로그램에서 사용자 이름이 이미 사용되었는지 여부를 확인하고 싶습니다. 이미 촬영 된 경우 오류가 표시됩니다.Angular2 재질 : 각진 입력에 대한 맞춤 검증

아래 가이드를 따르고 있습니다.
https://material.angular.io/components/input/overview#error-messages

타이프 스크립트 파일

import {Component} from '@angular/core'; 
import {FormControl, Validators} from '@angular/forms'; 

const existingUserNames = ['rohit', 'mohit', 'ronit']; 

@Component({ 
    selector: 'input-errors-example', 
    templateUrl: 'input-errors-example.html', 
    styleUrls: ['input-errors-example.css'], 
}) 
export class InputErrorsExample { 

    emailFormControl = new FormControl('', [ 
     Validators.required 
    ] 

    // I want to call below isUserNameTaken function but dont know 
    // how to use it with Validators so that error message will be visible. 

    isUserNameTaken() : boolean { 
     this.attributeClasses = attributeClasseses; 
     this.attributeClasses.find(object => { 
      if(object.attributeClass === this.attributeClass) { 
       console.log("found " + JSON.stringify(object)); 
       return true; 
      } 
     }); 
     return false; 
    } 
} 

HTML

<form class="example-form"> 
    <md-form-field class="example-full-width"> 
    <input mdInput placeholder="Email [formControl]="emailFormControl"> 
    <md-error *ngIf="emailFormControl.hasError('required')"> 
     Email is <strong>required</strong> 
    </md-error> 

    <!-- I want to make something like that - custom validation --> 

    <md-error *ngIf="emailFormControl.hasError('username-already-taken')"> 
     Username is already taken. Please try another. 
    </md-error> 
    <!-- custom validation end -->   

    </md-form-field> 

+0

아마이 글 https://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html 좀 봐? –

+1

당신은 그것을 작동 시키도록 관리 했습니까? 그렇다면 솔루션을 공유해주십시오. – jowey

답변

1
당신은 단지 매개 변수로 구성 요소를 받아 널 (null)을 반환하는 함수를 변경해야

모든 것이 정상이라면 오류 객체입니다. 그런 다음 구성 요소 유효성 검사기 배열에 배치하십시오.

// Control declaration 
emailFormControl = new FormControl('', [ 
    Validators.required, 
    isUserNameTaken 
] 

// Correct validator funcion 
isUserNameTaken(component: Component): ValidationErrors { 
    this.attributeClasses = attributeClasseses; 
    this.attributeClasses.find(object => { 
     if(object.attributeClass === this.attributeClass) { 
      console.log("found " + JSON.stringify(object)); 
      // found the username 
      return { 
       username-already-taken: { 
        username: component.value 
       } 
      }; 
     } 
    }); 
    // Everything is ok 
    return null; 
} 

그것은 Will Howell (그런데 감사) 의견에 넣어 링크에서 더 자세히 설명합니다. 또한 비 반응 형태에 대해서도 동일한 방법을 설명합니다.

Tutorial

관련 문제