2
Guys who can help me, I appreciate.
I have some reactive fields in my code, they become mandatory or not based on the previous field, my code is like this
<div class="ui-g-12 ui-md-4">
<msp-input-text id="nome" label="Qual é o nome da pessoa?" tooltip="teste" tooltip="teste"></msp-input-text>
</div>
<div class="ui-g-12 ui-md-4">
<msp-input-text id="nome-social" label="Possui nome social? se sim, qual?" tooltip="teste" tooltip="teste"></msp-input-text>
</div>
When informing the Name, the field Social-name becomes mandatory. If the user does not inform the Name, the field Social-name will be free from validation
until then had riding something like this
private setRequiredAndUpdateValidate(stringFormName: string[], group?: string) {
if (group) {
stringFormName.forEach(formName => {
this.form
.get(group)
.get(formName)
.setValidators([Validators.required]);
this.form
.get(group)
.get(formName)
.updateValueAndValidity();
});
} else {
stringFormName.forEach(formName => {
this.form.get(formName).setValidators([Validators.required]);
this.form.get(formName).updateValueAndValidity();
});
}
}
to then mount a validation in the field, below:
private verificaVeioPlantao() {
this.form.get('nome').valueChanges.subscribe(val => {
if (val) {
this.setRequiredAndUpdateValidate(['nome-social'], 'identidade');
} else {
this.clearValidatorsAndUpdateValidate([nome-social'], 'identidade');
}
});
}
There’s a way to simplify that?
I was thinking something like this ====>
onValidator(event: any): void {
if (this.form.get('nome').value === 'S') {
this.form.controls['nome-social'].setValidators([Validators.required]);
} else {
this.form.controls['nome-social'].clearValidators();
}
}
This second solution is much better, just don’t forget to use the takeUntil operator to avoid memory Leaks
– Eduardo Vargas
But to realize the second option, I had to implement the first, I added another method above, but this not working
– Fernanda Guimaraes