我试图在单击添加按钮时动态添加字段行。工作正常。问题是,当我单击添加按钮时,它将清除第一行值并添加新行。我所做的代码如下。
HTML:
<div id="ruleCriteria" style="padding: 20px;width: 100%;">
<mat-slide-toggle formControlName="evaluationCriteriaCondition">
Slide me!
</mat-slide-toggle>
<div id="ruleCriteriaFielDev" *ngFor="let ruleArray of ruleArrays; let i = index">
<mat-form-field style="width: 30%">
<mat-select [(value)]="selected[i]" [(ngModel)]="ruleArrays[i].field" formControlName="evaluationRuleField" id="evaluationRuleField" placeholder="Select value" name="evaluationRuleField">
<mat-option *ngFor="let evaluationRuleField of evaluationRuleFields" [value]="evaluationRuleField.value">
{{evaluationRuleField.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field style="width: 30%">
<mat-select formControlName="evaluationRuleOperator" [(ngModel)]="ruleArrays[i].operator" placeholder="Operation" id="evaluationRuleOperator" name="evaluationRuleOperator" required>
<mat-option>-- None --</mat-option>
<mat-option *ngFor="let operator of operators" [value]="operator.value">
{{ operator.viewValue }}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="example-full-width" style="width: 30%">
<input matInput formControlName="evaluationRuleValue" placeholder="Enter Value" [(ngModel)]="ruleArrays[i].ruleFieldvalue"id="evaluationRuleValue" name="evaluationRuleValue" required>
</mat-form-field>
<button mat-button (click)="addRuleRow(i)">+</button>
<button mat-button *ngIf="i > 0" (click)="deleteRuleRow(i)">x</button>
<mat-divider style="border-width: 6px;background:lightblue"></mat-divider>
</div>
</div>
TypeScript:
private ruleArrays: Array<any> = [{field:"",operator:"",ruleFieldvalue:""}];
private newAttribute: any = {}
evaluationRuleFields = [
{ value: "field_1", valueFieldType: 'text', viewValue: "Field 1" },
{ value: "field_2", valueFieldType: 'dropdown', viewValue: "Field 2" },
{ value: "field_3", valueFieldType: 'text', viewValue: "Field 3" },
{ value: "field_4", valueFieldType: 'multiselect', viewValue: "Field 4" },
{ value: "field_5", valueFieldType: 'dropdown', viewValue: "Field 5" }
]
operators = [
{ value: "equals", viewValue: "Equals" },
{ value: "notequalto", viewValue: "Not Equalto" },
{ value: "contains", viewValue: "contains" },
{
]
addRuleRow() {
this.ruleArrays.push(this.newAttribute)
}
答案 0 :(得分:2)
尝试一下
addRuleRow(item) {
this.ruleArrays.push(item)
}