我有一个屏幕,其中
input
字段根据 API 响应动态填充。每个输入字段都有一组与其关联的按钮。我只想在字段脏时才显示按钮。
以下是表格截图 -
我使用简单的
ngModel
来查看和更改值。由于字段没有任何复杂的验证,我不打算使用反应式表单方法。当用户在字段上键入时,应该出现相应的按钮集。单击任一按钮后,该字段应再次标记为原始状态。
下面是我填充模板的代码 -
<h5 class="mb-4">Report Configuration</h5>
<div class="form-group row" *ngFor="let config of reportConfig">
<label class="col-sm-12 col-md-4 col-form-label">{{config.title}} <span
class="text-danger">*</span></label>
<div class="col-sm-12 col-md-6 col-lg-6">
<input type="text" [class.is-invalid]="false" [id]="config.propertyKey" [(ngModel)]="config.propertyValue" class="form-control" />
<!-- On typing the field should be marked dirty & buttons should appear -->
</div>
<div class="col-sm-12 col-md-2 col-lg-2 pl-0">
<mat-icon class="mr-2" (click)="should mark the field pristine">check_small</mat-icon>
<mat-icon color="warn" (click)="should mark the field pristine">close_small</mat-icon>
</div>
</div>
这可以使用
ngModel
来实现吗?或者我只需要使用 FormArray
来实现这一点?
一个 ngModel 继承自 AbstractControlDirective,因此可以访问他的属性 valid、touched 或 dirty。为此,请使用模板引用变量(下面代码中的“#nameID”)
<div *ngFor="let config of reportConfig">
<input name="name" #nameID="ngModel" [(ngModel)]="config .name"/>
<button *ngIf="nameID.dirty">undo</button>
<pre>
{{nameID.control.dirty}} or {{nameID.dirty}}
{{nameID.control.touched}} or {{nameID.touched}}
{{nameID.control.valid}} or {{nameID.valid}}
</pre>
</div>
请记住,模板引用变量在 ngFor 下有自己的“范围”,因此使用它没有问题。
只需尝试将其添加到 html 中的 ngModel 中
(change)="checkDirty(value)"
此代码位于您的 ts 文件中
checkDirty(value) {
if (value.dirty) {
//your code on here
}
}
作为解释,ngModel 支持其中的 dirty 属性,并且在每个值更改中它将检查输入是否脏