Component transclude with inline template

后端 未结 2 1765
萌比男神i
萌比男神i 2021-01-05 07:50

I\'m using Angular 2-rc3 and have a Component and I want to apply transclusion, just in a bit of a different way. Here\'s my component:

import {         


        
相关标签:
2条回答
  • 2021-01-05 08:30
    • <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.

    • Binding events when using a ngForTemplate in Angular 2
    • ng-content select bound variable might be an approach that would allow to do something similar like you demonstrated in your question.
      It requires the user of your component to wrap the content in a <template> tag.
    0 讨论(0)
  • 2021-01-05 08:46

    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.

    0 讨论(0)
提交回复
热议问题