I have a form group that I need to show one of the required inputs whit ngIf. but even when this input does not exist, formcontrol check it and return form is not valid. my code is like this html:
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<label>mobile</label>
<input type="text" formControlName="mobile" />
<div *ngIf="!hasInfo">
<label>firstName</label>
<input type="text" formControlName="firstName" />
<label>lastName</label>
<input type="text" formControlName="lastName" />
</div>
<button type="submit">Submit</button>
</form>
ts:
constructor(){
this.formBuilder();
}
ngOnInit() {
if (accountResponse.length > 0) this.hasInfo= true;
}
formBuilder() {
this.myForm= new FormGroup({
mobile: new FormControl(null, Validator.required()),
firstName: new FormControl(null, Validator.required()),
lastName: new FormControl(null, Validator.required()),
});
}
onSubmit(){
if(this.myForm.valid){
console.log("valid")
}else{
console.log("not valid")
}
}
if hasInfo is true that not to show firstName and lastName, my form should return valid but is always not valid
*ngIf
on the template only. I would choose a different approach here and try to programmatically add or remove a control – user12163165