How to pass an expression to a component as an input in Angular2?

前端 未结 1 1615
故里飘歌
故里飘歌 2020-12-01 10:20

I need to pass an expression to a component that will be evaluated inside an component\'s template.

For example, component:

@Component({
  selector:          


        
相关标签:
1条回答
  • 2020-12-01 10:33

    Maybe one of this options can helps you:

    1) Using ngForTemplate input property of NgFor directive:

    Component

    @Component({
      selector: 'app-my-component',
      template: `
      <div *ngFor="let item of items template: itemTemplate"></div>`
    })
    export class MyComponent {
      @Input() items: any;
      @ContentChild(TemplateRef) itemTemplate: TemplateRef<any>;
    }
    

    Parent

    <app-my-component [items]="listOfItems">
      <ng-template let-item>[{{item.id}}] {{item.name}}</ng-template>
    </app-my-component>
    

    Plunker

    2) Using the NgTemplateOutlet directive

    Component

    @Component({
      selector: 'app-my-component',
      template: `
      <div *ngFor="let item of items">
        <ng-template [ngTemplateOutlet]="itemTemplate" [ngTemplateOutletContext]="{ $implicit: item }"></ng-template>
      </div>`
    })
    export class MyComponent {
      @Input() items: any;
      @ContentChild(TemplateRef) itemTemplate: TemplateRef<any>;
    }
    

    Parent remains the same:

    <app-my-component [items]="listOfItems">
      <ng-template let-item>[{{item.id}}] {{item.name}}</ng-template>
    </app-my-component>
    

    Plunker

    This way inside of <ng-template let-item>...</ng-template> you can use desired expression

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