2017-11-04 132 views
2

對不起,我的英語不好。Angular2異步驗證器

我試圖使用自定義異步驗證我的角度應用這樣

asyncValidator(control:FormControl):Promise<any>{ 
    const promise = new Promise<any>(
     (resolve, reject) =>{ 
     setTimeout(() => { 
      console.log("it works"); 
      resolve(null); 
     },5000); 
     } 
    ); 
    return promise; 
    } 

我宣佈我這樣的反應形式:

this.customForm = this.formbuilder.group({ 
     'userData': this.formbuilder.group({ 
     'name': ['',this.asyncValidator], 
     'email': [''], 
     }), 
     'pass': [''], 
     'gender': ['male'], 
     'hobbies': this.formbuilder.array([ 
     ['Reading'] 
     ]) 
    }) 

即使,在asyncValidator始終解析( null),名稱輸入仍然有ng無效的類。

enter image description here

回答

1

你正確地放在你的異步驗證。

它應該是:

'name': ['', null, this.asyncValidator], 
     (1) (2)   (3)  

其中:

(1) - 控制值

(2) - 同步驗證

(3) - 異步驗證

Stackblitz example

+0

非常感謝你,它的工作原理! :D –

+0

不客氣! – yurzui