2016-05-31 96 views
0

我试图创建一个简单的自定义验证器。基本上如果一个变量(代表)是真的,该字段必须是强制性的。就这样。Angular 2 - 自定义验证器问题

我不知道为什么,但我无法代表变量。它是未定义的。有关如何处理这个问题的任何线索?

behalf = false; 
private validateName(){ 
    if (this.behalf && this.nameB.text != '') { 
     return { 
      invalidName : true 
     }; 
    } 
    else{ 
     return null; 
    } 
}  
constructor (private builder: FormBuilder){ 
    this.title = new Control('', Validators.required); 
    this.name = new Control('', this.validateName); 
    this.type = new Control('', Validators.required); 
    this.desc = new Control(''); 
    this.hideTitle = new Control(''); 
    this.end = new Control('', Validators.required); 
    this.formBook = builder.group({ 
     title: this.title, 
     name: this.name, 
     type: this.type, 
     desc: this.desc, 
     hideTitle: this.hideTitle, 
     end: this.end 
    }); 
} 

回答

3

的问题是,您引用的函数,所以当这个函数被调用的this不对应的组件对象。

你可以尝试以下迫使功能的执行的组件实例的范围内:

this.name = new Control('', (control) => { 
    this.validateName(control); 
}); 

或使用bind方法:

this.name = new Control('', this.validateName.bind(this)); 

使用bind时要小心方法在TypeScript中:

0

嗨,我认为这种方法对你很有用。

addCustomerForm :any; 
constructor (private builder: FormBuilder){ 

this.customername = new Control("", Validators.compose([Validators.required, 
ValidationService.alphaValidator])); 

this.addCustomerForm = formBuilder.group({ 
    customername: this.customername, 
}); 

this.customerName = '';