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
566 views
in Technique[技术] by (71.8m points)

angular2 forms - Angular 2 FormGroup Add Validators dynamic

i'm tring to add validator to FormContol dynamic (not on initialization) and it's not work....

the code:

this.formGroup.controls["firstName"].validator = Validators.Required;
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Try this, it should work

this.formGroup.controls["firstName"].setValidators(Validators.required);

For multiple validators

this.formGroup.controls["firstName"].setValidators([Validators.required, Validators.minLength(2)]);

But doing so will override any validators that are provided during initialization

EDIT :

To reflect the form controls with newly added Validators immediately, we have to call this.formGroup.controls["firstName"].updateValueAndValidity(); after setting validators dynamically.

this.formGroup.controls["firstName"].setValidators(Validators.required);
this.formGroup.controls["firstName"].updateValueAndValidity();

DEMO for the same

* NOTE *

updateValueAndValidity() will trigger a valueChanges event even if the value didn't really change (potentially resulting in an infinite loop, if you're calling it from within a valueChanges subscription). You can prevent that by using the optional parameter object: { onlySelf: true, emitEvent: false}


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

2.1m questions

2.1m answers

60 comments

57.0k users

...