У меня есть этот компонент, который содержит таблицу (массив элементов значения ключа) и одну форму под ним. FOrm используется для добавления новых значений в таблицу. Есть Angular Код:
@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>
Когда я помещаю два из них в один шаблон и пытаюсь добавить таблицу (с помощью входы и нажмите на кнопку) оба списка добавляются. Это нормальное поведение? Как от этого избавиться?