我有一个组件A
和B
<div class="A">
<div class="A1"></div>
<div class="A2"></div>
</div>
<div class="B">
<!--want to display <div class="A1"></div> here-->
</div>
组件B
不包含组件A
或解决方法
<componentA></componentA>
<componentB></componentB>
我试图进行包装<div class="A1"></div>
,ng-template
然后在其中componentB
进行查询,但这始终是undefined
:
@ViewChild('templ') templ: TemplateRef<any>;
然后我意识到这@ViewChild
是查询子组件,那么如何查询和呈现<ng-template>
它不是子组件呢?
看看Alex Rickabaugh的这张出色的sideNav示例,该演示正是您所需要的。
在此基础上,你需要定义一个ng-container
你ComponentA
。然后,您需要ComponentB
使用自定义指令标记您的内容,并且有一个连接ComponentA
和的服务ComponentB
:
<div class="A1"><div>
<div class="A2" *leftNav >
<h3>Content</h3>
</div>
指示:
@Directive({
selector: '[leftNav]',
})
export class LeftNavDirective implements OnInit {
constructor(private leftNav: LeftNav, private ref: TemplateRef<any>) {}
ngOnInit(): void {
this.leftNav.setContents(this.ref);
}
}
服务:
@Injectable()
export class LeftNav {
private _state = new BehaviorSubject<TemplateRef<any>|null>(null);
readonly contents = this._state.asObservable();
setContents(ref: TemplateRef<any>): void {
this._state.next(ref);
}
clearContents(): void {
this._state.next(null);
}
}
最后,您ComponentB
必须在以下位置订阅您的<div class="A1"> ... <div>
东西ngAfterViewInit
:
ngAfterViewInit(): void {
this
.leftNav
.contents
.subscribe(ref => {
if (this._current !== null) {
this._current.destroy();
this._current = null;
}
if (ref === null) {
return;
}
this._current = this.vcr.createEmbeddedView(ref);
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句