Angular 2 passing html to ng-content with bindings

前端 未结 3 862
悲哀的现实
悲哀的现实 2020-12-08 10:41

I\'m writing angular components for the foundation css framework. I am working on the tabs component, and want to be able to pass some HTML to the

相关标签:
3条回答
  • 2020-12-08 11:04

    update Angular 5

    ngOutletContext was renamed to ngTemplateOutletContext

    See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

    original

    ngTemplateOutlet or ngForTemplate can be used for that use case:

    <tabs [data]='example'>
      <ng-template let-item>
        <div> Age <br> {{item.age}} </div>`
      </ng-template>
    </tabs>
    
    @Component({
      ...
      template: `
        <ul class="tabs" #tabs>
          <li *ngFor="let item of data | async" (click)="tabClick($event)">
              <a>{{item.name}}</a>
          </li>
        </ul>
        <div>
          <ng-template [ngTemplateOutlet]="templateRef" [ngTemplateOutletContext]="{$implicit: (data | async)}"></ng-template>
        </div>
      `
    })
    class TabsComponent {
      @ContentChild(TemplateRef) templateRef:TemplateRef;
    }
    

    See also Angular 2 bind transcluded content to loop variable

    0 讨论(0)
  • 2020-12-08 11:08

    You should be using this way instead,

    <tabs [data]='example'>
        <div> Age <br> {{item.age}} </div>`
    </tabs>
    

    Component typescript

    @Component({
      selector: 'tabs',
      templateUrl: './tabs.component.html'
    })
    
    export class TabsComponent {
      @Input() data:any;
      item:any{};
    }
    

    In your content projection define a selector as

     <div class="tabs-body">
            <ng-content select=".tabs-body"> </ng-content>
          </div>
    

    As your passing with bindings

    <tabs [data]='example'>
        <div> Age <br> {{item.age}} </div>`
    </tabs>
    

    DEMO

    0 讨论(0)
  • 2020-12-08 11:19

    You need to pass the item object to the ng-content component.

    <ng-content [item]="selectedTab></ng-content>
    

    I am not certain on what lies behind the tab click event but you can assign that item object to selectedTab which will be passed to the component.

    The component that will control the tab view can have the following:

    @Input() item: Item;
    

    And this will pass that object when you click. I might be attacking this from the wrong angle but maybe it will help you in some way.

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