Whenever I add a dynamic formControl via button click, all input fields that are required change color to invalid (red), my expectation is that only when the input is "touched" then form field will change to invalid color and only on the specific not all. I dont have a clue why this happen. I am just new to angular and angular material. Also i have pasted the whole html file.
Also this is my working example https://stackblitz.com/edit/angular-emman-sample?embed=1&file=src/app/app.component.html
<div>
<h2 mat-dialog-title>Add Company</h2>
<div mat-dialog-content>
<form [formGroup]="compAddFormGroup">
<div>
<ng-container *ngFor="let control of config">
<mat-form-field *ngIf="control.type === 'text' || control.type === ''">
<mat-label for="control.key">{{control.label}}</mat-label>
<input [required]="control.isRequired" matInput formControlName="{{control.key}}">
<mat-error *ngIf="compAddFormGroup.get(control.key).hasError('required') && compAddFormGroup.get(control.key).touched">{{getErrorMessage()}}</mat-error>
</mat-form-field>
<ng-container *ngIf="control.type === 'selectize'" [formArrayName]="control.key">
<ng-container *ngFor="let innerControl of compAddFormGroup.get(control.key).controls; let i = index">
<mat-form-field fxFlex floatLabel="always">
<mat-label for="innerControl">{{control.label}} <span *ngIf="i!=0">{{i+1}}</span></mat-label>
<input [required]="control.isRequired" matInput [formControl]="innerControl">
<button mat-button matSuffix (click)="addElem(control.key)" color="accent" class="addBtn" *ngIf="i === 0">Add</button>
<button matSuffix class="removePeriod" mat-icon-button disableRipple (click)="removeElem(control.key, i)" *ngIf="compAddFormGroup.get(control.key).length > 1 && i !== 0"><mat-icon>remove_circle</mat-icon></button>
<mat-error *ngIf="compAddFormGroup.get(control.key).controls[i].hasError('required') && compAddFormGroup.get(control.key).controls[i].touched"> {{getErrorMessage(control.key)}}</mat-error>
</mat-form-field>
</ng-container>
</ng-container>
</ng-container>
</div>
</form>
</div>
</div>
All of the formcontrols inside named as '[formControl]="innerControl"' so if one goes error all goes error. change the value something dinamic
Buttons inside forms are by default of type submit
. So what actually happens on add button click, is that the form is submitted, and angular material has the behavior that if a form is submitted, all required fields shows error. So that is what is going on currently. If you have a button inside form that shouldn't behave like submit, you need to explicitly say that it should be of type button
. So add type="button"
to those buttons:
<button (click)="addElem(control.key)" type="button">+</button>
<button (click)="removeElem(control.key, i)" type="button">-</button>
来源:https://stackoverflow.com/questions/57905372/text-color-of-all-required-input-field-change-to-invalid-color-when-adding-a-dyn