简体   繁体   English

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

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

I need to pass an expression to a component that will be evaluated inside an component's template. 我需要将表达式传递给将在组件模板中进行求值的组件。

For example, component: 例如,组件:

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

with component's template: 使用组件的模板:

<div *ngFor="let item of items">
  {{expression}}
</div>

Usage of MyComponent: MyComponent的用法:

<app-my-component [items]="listOfItems" [expression]="'[item.id] item.name'">
</app-my-component>

As there will be more than one input, I would like to avoid usage of TemplateRef. 由于将有多个输入,我想避免使用TemplateRef。

Maybe one of this options can helps you: 也许其中一个选项可以帮助您:

1) Using ngForTemplate input property of NgFor directive: 1)使用NgFor指令的ngForTemplate输入属性:

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 Plunker

2) Using the NgTemplateOutlet directive 2)使用NgTemplateOutlet指令

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 Plunker

This way inside of <ng-template let-item>...</ng-template> you can use desired expression 这样在<ng-template let-item>...</ng-template>您可以使用所需的表达式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM