用组件包装宿主内容的Angular指令



我想弄清楚如何编写以下场景:

app.component.html:

<div *appSlideOutDir>Hey there!</div>

指令代码是这样的:

export class SlideOutDirDirective implements OnInit {
constructor(
private viewContainer: ViewContainerRef,
private templateRef: TemplateRef<any>
) {}
ngOnInit() {
const slideOutComponent =
this.viewContainer.createComponent<SlideInComponent>(SlideInComponent);
slideOutComponent.instance.viewContainer.clear();
slideOutComponent.instance.viewContainer.createEmbeddedView(
this.templateRef
);
}
}

SlideOutComponent的代码如下:

export class SlideInComponent {
constructor(public viewContainer: ViewContainerRef) {}

它的模板是:

<div [class.slide-in]="show">
<ng-content></ng-content>
</div>

这个SlideOutComponent最初被用作一个组件,你可以包裹任何东西,并使它成为一个滑出的零食条(像在材料)类型的东西。然而,我想重用它,并在指令中使用它来实现同样的事情…

然而,当前的代码并没有在SlideOutComponent中注入Hey there!的原始内容,而是在它旁边注入一个兄弟元素:

<app-slide-in>...</app-slide-in>
<div>Hey there!</div>

我如何获得原始标签的Hey there!体与指令出现在<app-slide-in>内?

经过一番研究,我有了答案。

更改SlideOutComponent以接受templateRef作为输入。

@Input() controlTemplate: TemplateRef<any>;
然后,在HTML中,将ng-content更改为:
<ng-container *ngTemplateOutlet="controlTemplate">
</ng-container>

最后,改变:

slideOutComponent.instance.viewContainer.createEmbeddedView(
this.templateRef
);

:

slideOutComponent.instance.controlTemplate = this.templateRef;

这种方法对我来说很有效——我可以用标签包装任何组件。

最新更新