'How to set validation based on field selection in angular reactive form array

i try to implement angular reactive form array validation on based on other filed

    private addUserFormGroup(): FormGroup {
            return new FormGroup({
                'name': new FormControl('', Validators.required),
                'emailAddress': new FormControl('', Validators.required),
                'admin': new FormControl(false, Validators.required),
                'role': new FormControl(''),
            });
        }
        
         ngOnInit(): void {
            this.addUserForm = this.formBuilder.group({
                userList: this.formBuilder.array([this.addUserFormGroup()]),
            });
            
            this.addUserForm.valueChanges.subscribe((c) => {
                c.userList.forEach((x) => {
                    console.log(x.admin);
                    x['role'].validator = Validators.required;
                    // x.role.setValidators(Validators.required);
                });
            
            
            }

basically admin formcontrol as a checkbox, if i select admin checkbox i need to apply Validators.required to role filed.

could you please he me on this



Solution 1:[1]

You can subscribe to valueChanges of FormControl "admin" only so that it wont trigger on any other value changes.

And in subscribed method based on value true or false you can set the validator with setValidators function.

Inside value changes subscribed method you can either find the FormControl "role" using parent property of FormControl "admin"

or

if the structure is fixed you can get FormControl "role" with path also, like this.addUserForm.get("userList").get("0").get("role").setValidators(Validators.required);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1