我有这个组件,其中包含表(键值元素数组)及其下的一种形式。 FOrm用于将新值附加到表中。有角度代码:
@Component({
selector: 'app-key-value-table',
templateUrl: './key-value-table.component.html',
styleUrls: ['./key-value-table.component.css']
})
export class KeyValueTableComponent implements OnInit {
@Input() tableTitle: string;
@Input() records: KeyValue[];
@Input() prefix: string;
newRecordForm: FormGroup;
constructor(private fb: FormBuilder) {
}
ngOnInit() {
this.newRecordForm = this.fb.group({
key: ['',Validators.required],
value: ['',Validators.required]
});
}
deleteFromList(index: number) {
this.records.splice(index, 1);
}
addRow(formDirective: FormGroupDirective) {
if(this.newRecordForm.invalid)
return;
const newRecord = Object.assign({}, this.newRecordForm.value);
if(this.records.filter(elt=>elt.key === newRecord.key).length)
return
else {
this.records.push(newRecord);
formDirective.resetForm();
this.newRecordForm.reset();
}
}
}
还有HTML代码:
<table class="table">
<thead>
<tr>
<th scope="col">Identyfikator</th>
<th scope="col" class="wide">{{tableTitle}}</th>
<th scope="col">Edytuj</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let record of records; let index = index">
<th scope="row">{{record.key}}</th>
<td class="wide">{{record.value}}</td>
<td>
<button mat-icon-button (click)="deleteFromList(index)"><mat-icon>delete</mat-icon></button>
<button mat-icon-button [disabled]="index==(records.length-1)" (click)="moveLower(index)"><mat-icon>keyboard_arrow_down</mat-icon></button>
<button mat-icon-button [disabled]="index==0" (click)="moveHigher(index)"><mat-icon>keyboard_arrow_up</mat-icon></button>
</td>
</tr>
</tbody>
</table>
<div class="table-record-form">
<form [formGroup]="newRecordForm" #formDirective="ngForm" (ngSubmit)="addRow(formDirective)">
<mat-form-field [hideRequiredMarker]="false">
<input #key matInput placeholder="Identyfikator" formControlName="key" required>
<mat-hint align="end">{{key.value?.length || 0}}/50</mat-hint>
</mat-form-field>
<mat-form-field [hideRequiredMarker]="false">
<input #value matInput placeholder="Treść" formControlName="value" required>
<mat-hint align="end">{{value.value?.length || 0}}/250</mat-hint>
</mat-form-field>
<button name="submit-button" mat-raised-button color="primary" type="submit" [disabled]="newRecordForm.invalid">
Dodaj rekord
</button>
</form>
</div>
[当我将其中两个放在一个模板中,并尝试追加表时(使用输入并单击按钮),两个列表都将被追加。这是正常行为吗?如何摆脱它?
如果您有两个具有相同数据集的列表,即records
,则addRow
函数将应用于这两个表。我建议您有一个单独的数据集,例如records2
,然后可以在第二个表中使用。