每当我通过单击按钮添加动态formControl时,所有必需的输入字段都会将颜色更改为无效(红色),我的期望是,只有在“触摸”输入时,表单字段才会更改为无效颜色,并且仅在具体不是全部。我不知道为什么会这样。我刚接触角和角材料。我也粘贴了整个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>
答案 0 :(得分:0)
内部所有名为'[formControl] =“ innerControl”的formcontrol,因此,如果一个出错,所有错误都会出错。将值更改为动态
答案 1 :(得分:0)
默认情况下,表单内的按钮的类型为submit
。因此,单击添加按钮时实际发生的情况是提交了表单,并且棱角材料的行为是,如果提交了表单,则所有必填字段都显示错误。所以这就是目前正在发生的事情。如果您在表单中有一个按钮,其行为不应该类似于Submit,则需要明确声明其类型为button
。因此,将type="button"
添加到这些按钮:
<button (click)="addElem(control.key)" type="button">+</button>
<button (click)="removeElem(control.key, i)" type="button">-</button>