Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angularjs - Angular2 FormBuilder: Using 'this' in a custom validator

I'm developing a form using Angular2's FormBuilder with custom validation. Problem: In customValidator I'm using this to access the local object data. I'm getting a undefined error when the validation is executed.

It looks like the customValidator is executed in a different object and therefore changing the this reference

Question: How can I pass a reference of this to the customValidator?

export class Ast {
    public data:any;
    public myForm:FormGroup;

    constructor(private _fb:FormBuilder) {
        this.data = {foo: "bar"};
    }

    customValidator(c: FormControl) {
        if (this.data.foo == "bar") { // This line crashes
            // DO something
        }
    }

   ngOnInit() {
       this.myForm = this._fb.group({
           some_field: ['', [<any>Validators.required], this.customValidator]
       })
   }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using an arrow function, to make sure the function is bound to this:

some_field: ['', [<any>Validators.required], c => this.customValidator(c)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...