【发布时间】:2019-07-14 08:09:31
【问题描述】:
我想创建一个类似于工具提示控件的组件。问题是它只适用于简单的文本,但是当我想传递一个更复杂的 ng-template(如绑定等)时,它会中断。一般来说,我创建了一个主机组件,其中将显示传递的模板和一个创建组件的指令。 但似乎传递的上下文对于传递的模板不可见。
指令:
@HostListener("mouseenter")
enter() {
const factory = this.resolver.resolveComponentFactory(CustomContainerComponent);
const injector = Injector.create([]);
this.vcr.createComponent<CustomContainerComponent>(factory, 0, injector, this.generate());
}
generate(): any[][] {
const context = { // this is mocked for now
name:"John"
};
const viewRef = this.customControl.createEmbeddedView(context);
return [viewRef.rootNodes];
}
这里是 stackblitz 的一个简单例子: https://stackblitz.com/edit/angular-mzhccs
【问题讨论】:
-
在 app.component.html 上试试这个...值正在更新 - 但仅在第一个按钮上
<div style="display:flex; flex-direction:column;"> <button [customControl]="ctrl2">Working</button> <button [customControl]="ctrl1">Not working</button> </div> <ng-template #ctrl2> Working </ng-template> <ng-template #ctrl1 let-name="name"> not-working: {{name}} </ng-template> -
仍然无法与上下文绑定(名称未显示)。我已经设法让它工作,在指令中我将
this.customControl.createEmbeddedView(context);更改为this.vcr.createEmbeddedView(this.customControl, context);,现在它似乎工作了。
标签: angular angular2-template angular2-directives