簡體   English   中英

Angular 2將Component動態添加到DOM或模板

[英]Angular 2 append Component dynamic to DOM or template

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

然后我將其聲明為提供者,因此我可以調用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
  }

我認為您不需要將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
        });
  }
}

希望它對你有幫助,蒂埃里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM