Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

angular - Angular-将多个组件动态插入动态创建的DOM节点中(Angular - Dynamically insert multiple components into a dynamically created DOM node)

I'd like to create a DIV element with Renderer2 and then insert into it two or more components.

(我想使用Renderer2创建一个DIV元素,然后将两个或多个组件插入其中。)

import { HelloComponent } from './hello.component';

constructor(
    public renderer: Renderer2,
    public cfr: ComponentFactoryResolver,
    public elementRef: ElementRef,
    private injector: Injector,
    private applicationRef: ApplicationRef
    ) { }

ngOnInit() {    

  const newNode = this.renderer.createElement('div');
  this.renderer.appendChild(this.elementRef.nativeElement, newNode);

  let componentFactory = this.cfr.resolveComponentFactory(HelloComponent);
  let componentRef = componentFactory.create(this.injector, [], newNode);

  this.applicationRef.attachView(componentRef.hostView);

  componentRef.instance.name = "Component 1";

}

This code is ok for creating one component 'HelloComponent' inside the DIV, but I cannot find a way to add another component in the same DIV.

(此代码可以在DIV中创建一个组件“ HelloComponent”,但是我找不到在同一个DIV中添加另一个组件的方法。)

If I repeat the code with different variables then the second component is the only one that will be included in the DIV.

(如果我用不同的变量重复代码,则第二个组件将是唯一包含在DIV中的组件。)

Code on stackblitz

(Stackblitz上的代码)

  ask by lobsang translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...