Angular 2 append Component dynamic to DOM or template

后端 未结 2 1540
遥遥无期
遥遥无期 2020-12-29 11:28

I\'m planning to add a component dynamic to the DOM if show() is called. I know there is a solution with ngIf or [hidden] to hide it and use it as a directive, but I\'m not

2条回答
  •  别那么骄傲
    2020-12-29 12:02

    I don't think that you need to provide the Info component as providers to the other component. I'm not sure that it even works. You can leverage Query and QueryView to reference components used in another one:

    @Component({
      selector: 'Admin',
      templateUrl: './Admin.html',
      styleUrls: ['./Admin.css'],
      directives: [Info]
    })
    export class Admin{
      constructor(private @Query(Info) info: QueryList) {
        info.first().show(); <---- append the Info Element to DOM
      }
    }
    

    Instead of adding the element within the Info component, you can dynamically add this component using the DynamicComponentLoader as suggested by Günter:

    @Component({
      selector: 'Info',
      templateUrl: './components/pipes&parts/info.html',
      styleUrls: ['./components/pipes&parts/info.css']
    })
    
    export class Info{
          infoData: InfoData;
    
      public show(infoData: InfoData) {
        this.infoData= infoData;
        // No need to add the element dynamically
        // It's now part of the component template
        // document.body.appendChild(elemDiv); <----- Here?
      }
    }
    
    @Component({
      selector: 'Admin',
      //templateUrl: './Admin.html',
      // To show where the info element will be added
      template: `
        
    `, styleUrls: ['./Admin.css'], directives: [Info] }) export class Admin{ constructor(private dcl: DynamicComponentLoader, private eltRef:ElementRef) { this._dcl.loadIntoLocation(Info, this._el, 'dynamicChild') .then(function(el) { // Instance of the newly added component }); } }

    Hope it helps you, Thierry

提交回复
热议问题