选择视图很慢,但是当我有更多数据时,选择非常慢。
我使用了以下代码:
HTML
<div class="row">
<div class="input-field col s8">
<div formArrayName="data_id">
<div class="form-group" *ngFor="let itemm of editdataForm.get('data_id').value; let i = index">
<br>
<select formControlName="{{i}}" id="data_id" materialize="material_select" [materializeSelectOptions]="items"
[ngClass]="{invalid: invalidInputs}">
<option value="" disabled selected>Select Data</option>
<option *ngFor="let item of items" [value]="item.data_id">{{item.data_name}}</option>
</select>
<div class="button-left">
<button *ngIf="editdataForm.controls.data_id.value.length > 1" type="button" class="fa" (click)="onRemoveItem(i)">x</button>
</div>
</div>
</div>
</div>
<div class="input-field col s2">
<button type="button" class="btn" (click)="onAddData()">AddData</button>
</div>
</div>
TS
this.editdataForm= new FormGroup({
'data_id': this.fb.array([]),
.........
});
populateFormData() {
this.activatedRoute.params.subscribe(
params => {
this.hps.getdata(params['id']).subscribe(
data=> {
this.data= data;
....
this.data.sensors.forEach(x => {
(this.editdataForm.get('data_id') as FormArray).push(new FormControl(x.data_id))
});
}
);
}
);
}
onAddData() {
(<FormArray>this.editdataForm.controls['data_id']).push(new FormControl('', Validators.required));
}
onRemoveItem(index: number) {
(<FormArray>this.editdataForm.controls['data_id']).removeAt(index);
}
此代码效果很好,但是当有很多数据时非常慢。拜托,你能问我如何优化它的想法吗?如何使工作更快?
谢谢!
答案 0 :(得分:0)
您可以更改从后端获取数据的方式
populateFormData() {
this.activatedRoute.params.pipe(
flatMap(params => this.hps.getdata(params['id']))
).subscribe(
data=> {
this.data= data;
....
this.data.sensors.forEach(x => {
(this.editdataForm.get('data_id')as FormArray).push(new FormControl(x.data_id))
});
}
);
}
您还可以创建一个小的方法来轻松返回FormArray
get data_id ():FormArray {
return this.editdataForm.get('data_id')
}
,然后您来自populateFormData的代码将有所更改
来自(this.editdataForm.get('data_id')as FormArray).push(new FormControl(x.data_id))
将是this.data_id.push(new FormControl(x.data_id))
您还可以使用先前在html模板中创建的方法
更新
您可以做的主要改进是更改处理订阅以获取数据的方式。我分享的代码是您的操作方法,例如, 另一种方法只是使代码更简单,您可以使用自己的代码在表单数组中设置数据