[英]How to re-render component in Angular after subscribe
我在父組件中有以下代碼
在 parent.component.ts
constructor(private cdr: ChangeDetectorRef, private elementRef:ElementRef, private apiService: ApiService) {
}
ngOnInit() {
// Some Code
this.apiService.getFilters(this.metric).subscribe((results: FilterItem[][]) => {
this.cdr.detectChanges();
this.regionList = results[0];
this.subregionList=results[1];
})
// Some Code
}
在 parent.component.html
<app-filter-unit [checkBoxListActual]="regionList" [selectedCheckboxList]="selectedRegionList" (listUpdated)="updateRegions($event)">
</app-filter-unit>
在子組件 filter-unit.component.ts
checkBoxList: any[] = [];
@Input() selectedCheckboxList = ['ALL'];
@Output() listUpdated = new EventEmitter();
@Input() checkBoxListActual: any[] = [];
searchword: any="";
constructor(private cdr: ChangeDetectorRef) { }
ngOnInit() {
this.checkBoxListActual = [...new Set(this.checkBoxListActual)];
if(this.selectedCheckboxList && this.selectedCheckboxList.length > 0) {
if(this.selectedCheckboxList[0] == 'ALL') {
this.selectedCheckboxList.pop();
}
}
if(this.selectedCheckboxList.length == 0 ) {
this.selectedCheckboxList = [...this.checkBoxListActual];
}
this.checkBoxList = [...this.checkBoxListActual];
this.checkBoxList = [...new Set(this.checkBoxList)];
this.selectedCheckboxList = [...new Set(this.selectedCheckboxList)];
}
在 filter-unit.component.html
<div style="overflow: auto;height: 140px;">
<div *ngFor="let content of checkBoxList; let i=index" >
<span>
<input type="checkbox" name="unit-checkbox"
[checked]="selectedCheckboxList.indexOf(content) >= 0" value="content"
(change)="onClickCheckbox1(content, $event)">
</span>
<span> {{content}}</span>
</div>
</div>
當程序運行時,app-filter-unit 的“regionList”將為空,因為這是初始值。 但我有異步 api 調用 getFilters 來設置 regionList。 而且我希望 Angular 重繪 app-filter-unit,因為現在“regionList”將具有一定的價值。
這個怎么做?
如果您使用默認更改檢測,您的@Input() selectedCheckboxList
應該會自動更新。 但模板實際上綁定到checkBoxList
,您只在ngOnInit()
中對其進行初始化。
初始化FilterUnitComponent
后發生的更改永遠不會出現在checkBoxList
中,因此不會呈現。
如果您想對輸入的更改做出反應,您可以通過實現ngOnChanges()
來實現OnChanges 。 根據生命周期鈎子文檔:
在 ngOnInit() 之前以及一個或多個數據綁定輸入屬性更改時調用。
或者,您還可以為要響應的輸入定義設置器。 每次輸入更改時都會調用設置器。
private _selectedCheckBoxList: any[];
get selectedCheckBoxList(): any[] {
return this._selectedCheckBoxList;
}
@Input() set selectedCheckBoxList(value: any[]) {
this._selectedCheckBoxList = value;
// TODO: update this.checkBoxList
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.