cre*_*re8 0 angular2-forms angular
我正在尝试使用Angular2表单验证和魔杖来检查是否已经采用了该值:
namesArray = Users[];
ngOnInit() {
this.myForm = this.fb.group({
name: ['', Validators.compose([
Validators.required,
this.nameValidator
])
],
})
}
nameValidator(control:FormControl):{[key:string]:boolean} {
console.log(this.namesArray);
return null;
}
Run Code Online (Sandbox Code Playgroud)
这给我一个错误:
无法读取未定义的属性'namesArray'
当我打印时this返回undefined.那么如何访问函数之外的数组呢?
你需要传入胖箭头功能才能保留 this
ngOnInit() {
this.myForm = this.fb.group({
name: ['', Validators.compose([
Validators.required,
(control) => this.nameValidator(control as FormControl)
])
],
})
}
Run Code Online (Sandbox Code Playgroud)
有关胖箭头的更多信息,请访问:https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html