Typescript 如何重用包装Viewchild并对其进行更新的ngTemplate';内容
我希望使用动态更改的viewchild重用ng模板,并在重用ng模板的所有位置对其进行更新。然而,它并不是在所有地方都更新 当我将ng模板的内容设置为静态时,它会起作用,如下所示:Typescript 如何重用包装Viewchild并对其进行更新的ngTemplate';内容,typescript,angular7,viewchild,ng-template,Typescript,Angular7,Viewchild,Ng Template,我希望使用动态更改的viewchild重用ng模板,并在重用ng模板的所有位置对其进行更新。然而,它并不是在所有地方都更新 当我将ng模板的内容设置为静态时,它会起作用,如下所示: <h2>Position 1</h2> <ng-container [ngTemplateOutlet]="statusTemplate"></ng-container> <h2>Position 2</h2> <ng-container
<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>
然后我让这段代码动态地设置视图子级的内部内容,但是更新不会出现在我重复使用模板的两个地方
@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><!---->
位置1
成功
位置2
如何在多个位置更新重用的ng模板?为什么这不起作用?因此,您可以将类似的替代方案添加到组件中:
public status$: ReplaySubject<string> = new ReplaySubject();
若您需要根据状态传递html,您可以创建组件,该组件将根据状态传递html
<status-viewer [status]="status$ | async"><status-viewer>
我不会这样做(似乎更容易将h3的内容保存在变量中,然后简单地绑定它),但如果您想采用这种方法,我会使用
ViewChildren
而不是ViewChildren
import { Component, ViewChild, ViewChildren } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
@ViewChildren('status')
public statusElements: any;
public setStatusTo(name: string): void {
this.statusElements.toArray().forEach(
(status) => {
status.nativeElement.innerHTML = name;
}
)
}
}
您可以在这里看到整个过程:我认为更好的解决方案是使用组件,而不是
,并创建一些ReplaySubject来传递值这是一个简化的示例,你能举一个你推荐的例子吗?我用了一个异步ReplaySubject作为设置值,当我重用ngTemplate时,它仍然没有在所有地方更新。只有第一个。所以这个解决方案不起作用,所以我的错。我认为您可以只使用组件而不是ng模板
,它会工作的。没问题,谢谢您的努力。不幸的是,我的实际设置更复杂,这只是一个简单的问题示例。我必须使用view child和ng模板。出现的问题是viewchild选择器仅更新并选择一个视图子对象,但ngtemplate会重新使用它,这样就有多个视图子对象,并且它们不会全部更新。请注意:在我直接访问此.statusElements之前。\u结果是,但使用toArray()实际上“更干净”方法,这样我们就不会访问私有属性。但这两种方法都应该有效。
<status-viewer [status]="status$ | async"><status-viewer>
import { Component, ViewChild, ViewChildren } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
@ViewChildren('status')
public statusElements: any;
public setStatusTo(name: string): void {
this.statusElements.toArray().forEach(
(status) => {
status.nativeElement.innerHTML = name;
}
)
}
}