Angular 2 - 自定义验证器问题

Angular 2 - custom validators issues

我正在尝试创建一个简单的自定义验证器。基本上,如果一个变量(代表)为真,则该字段必须是强制性的。就这些了。

不知道为什么,我不能代表读取变量。它是未定义的。关于如何处理这个的任何线索?

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
    });
}

问题是您引用了一个函数,因此在调用此函数时 this 不对应于组件对象。

您可以尝试以下方法来强制在组件实例的上下文中执行函数:

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

或使用bind方法:

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

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

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

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 = '';