我有以下HTML:
<ul infraTooltip toolTipOptions="{check: 1}">
我创建了一个指令,在其主机上加载一个动态组件:
@Directive({
selector: '[infraTooltip]'
})
export class InfraTooltipDirective {
@Input() toolTipOptions: any = {};
constructor(private componentFactoryResolver: ComponentFactoryResolver,
private viewContainerRef : ViewContainerRef ) {
}
@HostListener('mouseenter', ['$event', '$target'])
showTooltip ($event) {
this.loadContainerComponent();
}
@HostListener('mouseleave', ['$event', '$target'])
hideTooltip ($event) {
this.clearContainerComponent();
}
loadContainerComponent () {
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(TooltipContainerComponent);
let componentInstance = this.viewContainerRef.createComponent(componentFactory);
componentInstance.instance.toolTipOptions = this.toolTipOptions;
}
我想根据指令的主机设置我的动态组件的样式 - 在我的情况下, ul ,以便实现类似于保留动态组件的功能:来自 ul 的10px。
答案 0 :(得分:1)
此机制称为View Encapsulation。您可以在Angular documentation on View Encapsulation中阅读更多内容。
父组件有两种可能的解决方案来设置子组件的样式。
答案 1 :(得分:1)
另一种方法:
@Component({
selector: '...',
})
class TooltipContainerComponent {
@HostBinding('style.left.px')
left:number = 0;
}
loadContainerComponent () {
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(TooltipContainerComponent);
let componentInstance = this.viewContainerRef.createComponent(componentFactory);
componentInstance.instance.toolTipOptions = this.toolTipOptions;
componentInstance.instance.left = 10;
}