簡體   English   中英

Angular2 ComponentResolver和ng-content不呈現

[英]Angular2 ComponentResolver and ng-content not rendering

我正在嘗試將ComponentResolverng-content一起使用,但是,當解析器構建組件時,不會呈現已轉換的內容。

我正在使用Angular2 RC3。 我知道有一些即將發生的變化可能會影響到ComponentResolverhttps://github.com/angular/angular/issues/9467 )。

import {
  Input, 
  Component, 
  OnInit, 
  ViewContainerRef, 
  ComponentResolver, 
  ViewChild 
} from '@angular/core';
/**
 * COLUMN
 */
@Component({
    selector: 'column-component',
    template: `
      <div style="border:1px solid green; padding:5px;display:block;">
        <b>column: {{label}}</b>
        <ng-content></ng-content>
      </div>`
})
export class ColumnComponent {
  @Input() label: sting = "";
}
/**
 * CELL
 */
@Component({
    selector: 'cell-component',
    template: '<b>cell component</b> <div #target></div>'
})
export class CellComponent {

  @ViewChild('target', {read: ViewContainerRef}) target;

  constructor(
    private componentResolver:ComponentResolver, 
    private viewContainerRef: ViewContainerRef) {
  }

  ngOnInit() {
    this.componentResolver.resolveComponent(ColumnComponent).then((factory) => {
      let componentRef = this.target.createComponent(factory, 0, this.viewContainerRef.injector);
    });
  }
}
/**
 * TABLE
 */
@Component({
    selector: 'datatable',
    template: `
      <div #target style="border:1px solid blue;padding:5px;">
        <b>table component</b>
        <cell-component
           style="border:1px solid yellow;padding:5px;display:block">
         </cell-component>
      </div>
    `,
    directives: [ CellComponent ]
})
export class TableComponent {
}
/**
 * ROOOT APP
 */
@Component({
    selector: 'root-app',
    template: `
      <div style="border:1px solid red;padding:5px;">
        <datatable>
          <column-component [label]="'my label'">
            column content
          </column-component>
        </datatable>
      </div>
    `,
    directives: [ ColumnComponent, TableComponent ]
})
export class AppComponent {

}

當前行為:永遠不會呈現作為column-component內容的單詞“列內容”。

預期行為column-component的內部內容(單詞“列內容”)將呈現。


UPDATE

@GünterZöchbauer回答了我的問題(謝謝!),然而,我應用了更多的邏輯,遺憾的是它沒有用。 請參閱更新的plunkr: https ://plnkr.co/edit/CsbmY6wePC3AWZlBDy34 p = preview

預期結果:將對每一行重復單元格,並將rowage屬性的值轉換為每行。

您還需要將<ng-content>添加到中間組件

Plunker的例子

暫無
暫無

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

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