【问题标题】:Angular 2 append Component dynamic to DOM or templateAngular 2 将组件动态附加到 DOM 或模板
【发布时间】:2016-04-23 16:22:50
【问题描述】:

如果调用 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?
    }
  }

然后我将其声明为 Provider,以便我可以调用 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
  }

【问题讨论】:

    标签: javascript components angular


    【解决方案1】:

    【讨论】:

    【解决方案2】:

    我认为您不需要将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
      }
    }
    

    您可以按照 Günter 的建议,使用 DynamicComponentLoader 动态添加此组件,而不是在 Info 组件中添加元素:

    @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
            });
      }
    }
    

    希望对你有帮助 蒂埃里

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 2018-01-04
    • 2018-12-05
    • 2022-11-19
    • 1970-01-01
    相关资源
    最近更新 更多