gpt4 book ai didi

angular - 将组件动态附加到 Angular 5 中的 div

转载 作者:太空狗 更新时间:2023-10-29 17:53:42 26 4
gpt4 key购买 nike

我有这个

https://angular-dynamic-component-append.stackblitz.io/

我设法动态附加了一个元素,但它没有被编译。我看到很多教程,例如 this

但这并不是我真正需要的。他们通常使用主题标签符号来标识容器。

我需要将一个组件附加到任何可能有的元素我的自定义指令。

我还需要使用指令的绑定(bind)值来控制附加元素上的 [hidden] 属性。

目标

  1. 覆盖现有组件的行为:
    • 添加一个属性来显示/隐藏
    • 添加一个类来自定义外观
  2. 减少 html 编码
    • 无需编写整个组件<my-comp></mycomp>
    • 不需要知道类
    • 类名改变时的自动行为
      1. 更改应用指令的元素
    • 最终目标是向容器元素添加一个类

预期来源

<div [myDirective]="myBoolean">
<p>some content</p>
</div>

预期编译

<div [myDirective]="myBoolean" class="myDirectiveClass1">
<p>some content</p>
<someComponent [hidden]="myBoolean" class="myDirectiveClass2"></someComponent>
</div>

有什么办法可以实现吗?

提前致谢

最佳答案

这很简单。我只是给你举了个例子。

请阅读 loader 指令中的注释。

https://github.com/garapa/studying/tree/master/loader

编辑:

你的组件:

export class LoaderComponent {

loading;

constructor() { }

}

你的指令

export class LoaderDirective implements OnDestroy {

private componentInstance: ComponentRef<LoaderComponent> = null;

@Input()
set appLoader(loading: boolean) {
this.toggleLoader(loading);
}

constructor(
private viewContainerRef: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver
) { }

toggleLoader(loading: boolean) {
if (!this.componentInstance) {
this.createLoaderComponent();
this.makeComponentAChild();
}

this.componentInstance.instance.loading = loading;
}

private createLoaderComponent() {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(LoaderComponent);
this.componentInstance = this.viewContainerRef.createComponent(componentFactory);
}

private makeComponentAChild(){
const loaderComponentElement = this.componentInstance.location.nativeElement;
const sibling: HTMLElement = loaderComponentElement.previousSibling;
sibling.insertBefore(loaderComponentElement, sibling.firstChild);
}

ngOnDestroy(): void {
if (this.componentInstance) {
this.componentInstance.destroy();
}
}

}

你的模块

@NgModule({
...
entryComponents: [
LoaderComponent
]
})

关于angular - 将组件动态附加到 Angular 5 中的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48410996/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com