【问题标题】:Angular2 ComponentResolver and ng-content not renderingAngular2 ComponentResolver 和 ng-content 未呈现
【发布时间】:2016-10-29 12:39:00
【问题描述】:

我正在尝试同时使用ComponentResolverng-content,但是,当解析器构建组件时,不会渲染转入的内容。

我正在使用 Angular2 RC3。我知道ComponentResolver (https://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 的内部内容(单词“列内容”)将呈现。


更新

@GünterZöchbauer 回答了我的原始问题(谢谢!),但是,我应用了更多逻辑,遗憾的是它没有用。查看更新的 plunkr: https://plnkr.co/edit/CsbmY6wePC3AWZlBDy34?p=preview

预期结果:单元格将针对每一行重复,rowage 属性的值将被转置到每个单元格。

【问题讨论】:

  • 请在plunker上添加一个简单的demo
  • “标记”来自什么标记?
  • @yurzui 添加了 plunkr。
  • 预期的行为是什么?
  • @GünterZöchbauer 已更新 :)

标签: angular


【解决方案1】:

您还需要将&lt;ng-content&gt; 添加到中间组件

Plunker example

【讨论】:

猜你喜欢
  • 2019-04-22
  • 2017-09-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 2017-03-17
  • 2016-10-24
  • 2014-03-14
相关资源
最近更新 更多