2017-11-04 129 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