Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

<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.

like image 663
Marin Relatic Avatar asked Oct 11 '16 09:10

Marin Relatic


People also ask

Can we pass component as input in Angular?

Firstly, we have to create a custom property to pass the data into a component. This can be done via input binding, which passes data from one component to another, generally from parent to child. This custom input binding is created by using the @Input() decorator.

How do I pass a string to a component?

@Input decorator: A string can be passed from a parent component to a child component using @Input decorator in class and a directive property of component decorator.


1 Answers

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

like image 71
yurzui Avatar answered Oct 14 '22 10:10

yurzui