我想将ng模板与动态更改的viewchild一起使用,并在所有我重复使用ng-template的地方进行更新。但是,它并不会在所有地方更新。
当我像这样使ng-template的内容静态化时,它起作用:
<h2>Position 1</h2>
<ng-container [ngTemplateOutlet]="statusTemplate"></ng-container>
<h2>Position 2</h2>
<ng-container [ngTemplateOutlet]="statusTemplate"></ng-container>
<ng-template #statusTemplate>
<h3>Saved</h3>
</ng-template>
输出以下HTML:
但是,当我将ng-template内的h3
设为一个视图子级并尝试动态更新它时,它不会在两个地方都更新。
例如
<h2>Position 1</h2>
<ng-container [ngTemplateOutlet]="statusTemplate"></ng-container>
<h2>Position 2</h2>
<ng-container [ngTemplateOutlet]="statusTemplate"></ng-container>
<ng-template #statusTemplate>
<h3 #status></h3>
</ng-template>
然后我用这段代码动态地设置了view child的内部内容,但是在我重复使用模板的两个地方都没有出现更新
@ViewChild('status', { static: false })
public status: any;
public setStatusTo(name: string): void {
this.status.nativeElement.innerHTML = name;
}
在浏览器中运行时html看起来像这样
<h2 _ngcontent-rdv-c3="">Position 1</h2>
<!--bindings={
"ng-reflect-ng-template-outlet": "[object Object]"
}-->
<h3 _ngcontent-rdv-c3="">Success</h3>
<h2 _ngcontent-rdv-c3="">Position 2</h2>
<!--bindings={
"ng-reflect-ng-template-outlet": "[object Object]"
}-->
<h3 _ngcontent-rdv-c3=""></h3><!---->
我如何在多个地方实现对重复使用的ng-template的更新?为什么这行不通?
答案 0 :(得分:1)
我不会这样做(将h3的内容保存在变量中然后简单地绑定它似乎更容易),但是如果您想采用这种方法,我会使用ViewChildren
而不是{{ 1}}
ViewChild
您可以在这里看到整个工作:https://stackblitz.com/edit/angular-af19ma
答案 1 :(得分:0)
因此,与替代方法一样,您可以将其添加到您的组件中:
public status$: ReplaySubject<string> = new ReplaySubject();
,然后改为使用h3
{{status$ | async}}
如果您需要根据状态传递html,则可以创建组件来根据状态进行操作。
<status-viewer [status]="status$ | async"><status-viewer>