Dynamically load component in div - Angular5

前端 未结 1 1288
面向向阳花
面向向阳花 2021-02-14 08:45

I was able to successfully create a button that on click loads another instance of my component into the DOM, but it loads it outside the component I want it to be inside which

相关标签:
1条回答
  • 2021-02-14 09:23

    You need to use your own ViewContainerRef. Currently you injecting root one and as you can see all your components appended to <app-root>.

    import { Component, OnInit, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
    import { EditorComponent } from '../editor/editor.component';
    
    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.scss']
    })
    export class HomeComponent implements OnInit {
      // Setup custom viewChild here
      @ViewChild('container', { read: ViewContainerRef }) viewContainerRef: ViewContainerRef;    
    
      constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
    
      ngOnInit() {
      }
    
      addEditor() {
        const factory = this.componentFactoryResolver.resolveComponentFactory(EditorComponent);
        const ref = this.viewContainerRef.createComponent(factory);
        ref.changeDetectorRef.detectChanges();
      }
    
    }
    

    Now inside your home.component.html put this where you want your editors to be instantiated

    <div #container></div>
    

    You can use any html tag here.

    Now all your editors will be inside this block.

    0 讨论(0)
提交回复
热议问题