如何将表达式作为Angular2中的输入传递给组件?

Mar*_*tic 9 angular2-components angular

我需要将表达式传递给将在组件模板中进行求值的组件.

例如,组件:

@Component({
  selector: 'app-my-component',
  ...
})
export class MyComponent {
  @Input items: MyClass;
  @Input expression: String;
  ...
}
Run Code Online (Sandbox Code Playgroud)

使用组件的模板:

<div *ngFor="let item of items">
  {{expression}}
</div>
Run Code Online (Sandbox Code Playgroud)

MyComponent的用法:

<app-my-component [items]="listOfItems" [expression]="'[item.id] item.name'">
</app-my-component>
Run Code Online (Sandbox Code Playgroud)

由于将有多个输入,我想避免使用TemplateRef.

yur*_*zui 19

也许其中一个选项可以帮助您:

1)使用ngForTemplateNgFor指令的输入属性:

零件

@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>;
}
Run Code Online (Sandbox Code Playgroud)

<app-my-component [items]="listOfItems">
  <ng-template let-item>[{{item.id}}] {{item.name}}</ng-template>
</app-my-component>
Run Code Online (Sandbox Code Playgroud)

Plunker

2)使用NgTemplateOutlet指令

零件

@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>;
}
Run Code Online (Sandbox Code Playgroud)

家长保持不变:

<app-my-component [items]="listOfItems">
  <ng-template let-item>[{{item.id}}] {{item.name}}</ng-template>
</app-my-component>
Run Code Online (Sandbox Code Playgroud)

Plunker

这样<ng-template let-item>...</ng-template>你内心就可以使用所需的表达方式