Angular2: Conditional required validation

懵懂的女人 提交于 2019-11-30 13:09:48

I had a similar problem but couldn't find a answer. Since nobody has answered this yet I'll provide an example of how I solved my problem, and how you can solve your issue using the same solution.

Example: (Phone number is required only if email is not set)

export class UserComponent implements OnInit {

userForm: FormGroup;

constructor(private fb: FormBuilder) {}

ngOnInit() {

    //Create my userForm and and add initial validators
    this.userForm = this.fb.group({
        username: [null, [Validators.required]],
        name: [null, [Validators.required]],
        email: [],
        phoneNumber: [null, [Validators.required, Validators.minLength(4)],
    });

    //Listen to email value and update validators of phoneNumber accordingly
    this.userForm.get('email').valueChanges.subscribe(data => this.onEmailValueChanged(data));
}


onEmailValueChanged(value: any){
    let phoneNumberControl = this.userForm.get('phoneNumber');

    // Using setValidators to add and remove validators. No better support for adding and removing validators to controller atm.
    // See issue: https://github.com/angular/angular/issues/10567
    if(!value){
        phoneNumberControl.setValidators([Validators.required, Validators.minLength(4)]);
    }else {
        phoneNumberControl.setValidators([Validators.minLength(4)]);
    }

    phoneNumberControl.updateValueAndValidity(); //Need to call this to trigger a update
}

}

So in your case you should add a changeListener to "_ansat" equal to my email listener, and then add required to "_helbred" accordingly.

Just add validator for the field:

if(some_logic) {
 this.your_form.get('field_name').setValidators([Validators.required]);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!