I generate multiple forms in my angular app with *ngFor
and all the submit buttons get disabled/ enabled when I change just a single input field.
I want the button of a corresponding input field to disable/ enable when only the input field of the correpsonding form changed, not when any input field of any form changes.
I can't come up with a solution or an alternative right now. Any idea?
My html code:
<mat-card *ngIf="myText">
<h1 mat-header class="center">My texts</h1>
<mat-card-content>
<div *ngFor="let item of myText">
<h3 mat-subheader class="center">myText {{ item.index + 1 }}</h3>
<p class="message">{{ item.textmessage }}</p>
<form [formGroup]="myTextForm" class="myText-form" (ngSubmit)="sendPrompt(item.index)">
<mat-form-field class="full-width" *ngIf="!error">
<mat-label>Respond to text</mat-label>
<textarea
matInput
cdkTextareaAutosize
cdkAutosizeMinRows="3"
cdkAutosizeMaxRows="20"
formControlName="prompt"
required="true"
></textarea>
</mat-form-field>
<p>
<button mat-raised-button class="btn" color="primary" [disabled]="myTextForm.invalid" type="submit">
Respond
</button>
<button
mat-raised-button
color="accent"
[cdkCopyToClipboard]="item.textmessage"
>
Copy to clipboard
</button>
</p>
</form>
<mat-divider *ngIf="item.index + 1 < myText.length"></mat-divider>
</div>
</mat-card-content>
</mat-card>
Any help or tips are much appreciated.
EDIT: Daniel Vágners answer did the trick for me. Thanks!
It would be great to receive the component.ts corresponding to the HTML.
Based on what I know from you and if I understand correctly. I suggest that the problem here is that you're using the same FormGroup for every form in your loop (myTextForm). Create a separate FormGroup for each form. This would isolate the validation for each form, and each submit button.
First of all create aray and init form
myTextForms: FormArray = new FormArray([]);
// init form mostly on ngOnInit or when your data are ready
initForms() {
for (const item of this.myText) {
this.myTextForms.push(new FormGroup({
'prompt': new FormControl('', Validators.required)
}));
}
}
After that modify your formGroup and submitButton so it will use the FormArray and accesses each FormGroup by index.
<form [formGroup]="myTextForms.at(i)" class="myText-form" (ngSubmit)="sendPrompt(item.index)">
and
<button mat-raised-button class="btn" color="primary" [disabled]="myTextForms.at(i).invalid" type="submit">
Respond
</button>