【问题标题】:List item renderer in Angular 2Angular 2 中的列表项渲染器
【发布时间】:2016-08-25 06:35:27
【问题描述】:

我得到了“哑”列表组件,它使用另一个“哑”组件来呈现单个项目。当我想将数据传递给渲染器时,我的列表组件中必须有相同的属性。例如,如果我想为项目设置“showTimestamp”布尔属性,我必须这样做:

list.template.html

<my-item-renderer *ngFor="let item of items" [showTimestamp]="showTimestamp"></my-item-renderer>

有没有办法替换部分组件模板?

我想做这样的事情:

<my-list [items]="items"><ng-content><item-renderer [showTimestamp]="true"></item-renderer></ng-content></my-list>

所以我的列表只获得了 items 属性,并且在 ng-content 中获得了一个已设置 showTimestamp 变量的渲染器。

【问题讨论】:

    标签: templates angular


    【解决方案1】:

    您可以为此使用模板:

    <my-list [items]="items">
      <template><item-renderer [showTimestamp]="true"></item-renderer></template></my-list>
    
    @Component({
      selector: 'my-list',
      template: `
          <template ngFor [ngForOf]="items" [ngForTemplate]="templateRef"></template>`
    })
    class MyList {
      @Input() data;
      constructor(private templateRef:TemplateRef) {}
    }
    

    另见

    【讨论】:

    • 在使用您的代码时,运行时出现“No provider for TemplateRef”错误。
    • 第二个和第三个链接使用@ContentChild(TemplateRef) templateRef: TemplateRef&lt;any&gt;;而不是构造函数注入。你能试试吗?我自己用了一段时间。
    • 谢谢! @ContentChild(TemplateRef) templateRef: TemplateRef; 正在工作。
    猜你喜欢
    • 2017-09-06
    • 2018-12-13
    • 2017-10-31
    • 2017-04-05
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    相关资源
    最近更新 更多