Component transclude with inline template

回眸只為那壹抹淺笑 提交于 2019-11-30 20:12:54
Richard Matsen

To spell out the ngForTemplate method:

(As of Angular 4 the element is now called <ng-template>.)

  1. Use a <template> tag in both the outer and inner components, instead of <ng-content>.

  2. The <li> is moved to the app.component html, and the <template> on this component has a special 'let-' attribute which references the iterated variable in the inner component:

    <my-list [data]="cars">
      <template let-item>
        <li>
          <div>{{item.make | uppercase}}</div>
        </li>
      </template>
    </my-list>
    
  3. The inner component has <template> as well and uses a variant of ngFor like so:

    <ul>
        <template #items ngFor [ngForOf]="data" [ngForTemplate]="tmpl">
            -- insert template here --
        </template>
    </ul>
    
  4. The 'tmpl' variable assigned to the ngForTemplate attribute needs to be fetched in the component code:

    export class MyListComponent {
        @Input() data: any[];
        @ContentChild(TemplateRef) tmpl: TemplateRef;
    }
    
  5. @ContentChild and TemplateRef are angular bits, so need to be imported

    import { Component, Input, ContentChild, TemplateRef } from '@angular/core';
    

See the fork of your plunkr with these changes in here plnkr.

This isn't the most satisfactory solution for your stated problem, since you're passing the data in to the list you might as well have the ngFor on the outer. Plus, the additional content (the literal '-- insert template here --') gets dropped, so it you wanted to display that it must be on the outer template as well.

I can see it might be useful where the iteration is provided within the inner component (say from a service call), and maybe to do some manipulation of the template in code.

Günter Zöchbauer
  • <ng-content> inside *ngFor doesn't work, therefore

    <li *ngFor="let item of data">
        -- insert template here --
        <ng-content></ng-content>
    </li>
    

won't do anything meaningful. Everything will be transcluded to the first <ng-content>

https://github.com/angular/angular/issues/8563 might solve some of your requirements.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!