Angular 2将Component动态添加到DOM或模板

use*_*579 12 javascript components angular

如果调用show(),我打算在DOM中添加一个动态组件.我知道有一个使用ngIf或[hidden]的解决方案来隐藏它并将其用作指令,但我不是这个解决方案的粉丝,因为我不想在我的HTML中声明它.

  import {Component} from 'angular2/core';
  import {InfoData} from '../../model/InfoData';

  @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;
      document.body.appendChild(elemDiv); <----- Here?
    }
  }
Run Code Online (Sandbox Code Playgroud)

然后我将其声明为提供者,因此我可以调用show().

  import {Component} from 'angular2/core';
  import {Info} from './components/pipes&parts/Info';

  @Component({
    selector: 'Admin',
    templateUrl: './Admin.html',
    styleUrls: ['./Admin.css'],
    directives: [Info],
    providers: [Info]
  })

  export class Admin {
    constructor(private info: Info) {
    info.show(); <---- append the Info Element to DOM
  }
Run Code Online (Sandbox Code Playgroud)

Thi*_*ier 6

我认为您不需要将Info组件作为提供程序提供给其他组件.我不确定它是否有效.您可以利用QueryQueryView引用另一个中使用的组件:

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

Info您可以使用DynamicComponentLoaderGü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: `
    <div #dynamicChild>
      <!-- Info component will be added here -->
    </div>
  `,
  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
        });
  }
}
Run Code Online (Sandbox Code Playgroud)

希望它对你有帮助,蒂埃里

  • `DynamicComponentLoader`现已弃用:( (3认同)
  • @NoémiSalaün是的,但这个Günter的答案可能让你感兴趣:http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 ;-) (2认同)