使用ngIf和Observable更新ng模板内的角度数据



模板:

<ng-template #rightPanelContent>
<si-right-panel-content [heading]="">
<h1>HEAD No NGIF</h1>
<div *ngIf="cpDevices$ | async as cpDevices">
...
</div>
</si-right-panel-content>
</ng-template>

ViewChild:

@ViewChild('rightPanelContent', { static: false }) set setrightPanelContent( rightPanelContent: TemplateRef<unknown>) {
if(rightPanelContent){
console.log("ViewChild updated");
this.rightPaneltemplate = new TemplatePortal(
rightPanelContent,
this._viewContainerRef
);
}
}

当点击按钮时,我需要用更新的数据设置右面板内容,但问题是,在调用处理按钮点击的函数后,右面板内容会更新。我只需要在正确的位置注入这行(更新后(。

this.rightPanelService.setRightPanelContent(this.rightPaneltemplate);

我找到了一个使用TemplatePortal的解决方案:


ngAfterViewInit () {
this.rightPaneltemplate = new TemplatePortal(
this.rightPanelContent,
this._viewContainerRef
);

点击按钮时,用更新的数据设置右侧面板内容


this.rightPanelService.setRightPanelContent(this.rightPaneltemplate);

那么使用BehaviorSubject 跟踪cpDevices$可观察值是很重要的

@组件:

private readonly cpDeviceWithSensorsSub = new BehaviorSubject<CpDevices>(undefined);
constructor(){
...
this.cpDevices$ = this.cpDeviceWithSensorsSub.asObservable();
}
ngOnInit() {
...
this.cpDeviceSubscription = (// when receive the data//).subscribe(value => this.cpDeviceWithSensorsSub.next(value));
}

角度模板门户文档

最新更新