如何将组件添加到 elementref 中?

Sac*_*han 9 angular

我想将一个组件作为子项添加到 elementref 中并可以访问它的属性。

const element: HTMLElement = document.createElement('div');

element.innerHTML = // Component needs to be added here

// Need to have access to properties of the Component here
Run Code Online (Sandbox Code Playgroud)

我在我的项目中添加了一个完整的日历,对于时间线,我需要添加自定义资源元素。为此,我只能访问 HTMLElement 和一些数据。所以我想要做的是将一个初始化的组件传递给 HTMLElement。

现在我唯一的选择是将 html 编写为字符串并将其传递给 innerHTML。有更好的选择吗?

pra*_*jha 10

在我的一个项目中,我以这种方式实现了与您的要求类似的东西。让我知道它是否有帮助?

constructor(private componentFactoryResolver: ComponentFactoryResolver,
            private injector: Injector, 
            private appRef: ApplicationRef) {
  const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent); // Your dynamic component will replace DynamicComponent

  const componentRef = componentFactory.create(this.injector);

  this.appRef.attachView(componentRef.hostView);  

  const domElem = (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;

  const element: HTMLElement = document.createElement('div');
  element.appendChild(domElem); // Component needs to be added here
  document.body.appendChild(element);
}
Run Code Online (Sandbox Code Playgroud)

这样你就可以参考你的动态组件 componentRef


Rob*_*hof 5

您也许可以使用Renderer2

export class AppComponent { 
@ViewChild('addButton') 
  private animateThis: ElementRef;  
  constructor(private renderer: Renderer2) {}

  addBtn() {
    const button = this.renderer.createElement('button'); 
    const buttonText = this.renderer.createText('This is a button');
    this.renderer.appendChild(button, buttonText);
    this.renderer.appendChild(this.animateThis.nativeElement, button);
  }
}
Run Code Online (Sandbox Code Playgroud)

更多例子

  • 我只是从字面上解释了 (4认同)
  • 这更好,因为现在 Angular 可以感知 DOM 的变化。仅将其附加到 DOM 中,角度就不会意识到这一点。 (2认同)