添加动态窗体控件时,所有必需输入字段的文本颜色将更改为无效颜色



>每当我通过按钮单击添加动态表单控件时,所有必需的输入字段都会将颜色更改为无效(红色(,我的期望是,只有当输入被"触摸"时,表单字段才会更改为无效颜色,并且仅在特定的不是全部。我不知道为什么会发生这种情况。我只是对角度和角度材料不熟悉。我也粘贴了整个 html 文件。

这也是我的工作示例 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>

里面的所有表单控件都命名为"[formControl]="innerControl",所以如果一个出错,所有的东西都会出错。 更改值 一些 迪纳米克

表单中的按钮默认为submit类型。因此,单击添加按钮时实际发生的是表单已提交,并且角度材料具有以下行为:如果提交表单,则所有必填字段都会显示错误。这就是目前正在发生的事情。如果你在表单中有一个按钮,它的行为不应该像提交,你需要明确地说它应该是类型button。因此,请向这些按钮添加type="button"

<button (click)="addElem(control.key)" type="button">+</button>
<button (click)="removeElem(control.key, i)" type="button">-</button>

最新更新