Reputation: 341
I wonder if it's possible to use an arrow function in a component like this in Angular
<app-child [showItemCondition]="item => item.isVisible" [list]="items"></app-child>
Upvotes: 8
Views: 9419
Reputation: 38134
Any functions cannot be defined in templates. To make it possible, then we need to eval those code in JIT compilation mode.
Prohibition to use arrow function allows to get rid of unnecessary code (DRY and KISS) and as a result:
If you need a function, it should be defined as component class method. It can be either regular or arrow function.
If logic will be placed in template, it means:
Upvotes: 3
Reputation: 57939
As Guerric say, is not possible, you should defined, e.g.
condition=(item)=>item.isVisible
//or
condition=(item)=>{
return item.isVisible
}
condition(item){
return item.isVisible
}
And pass the function as arg
<app-child [showItemCondition]="condition" [list]="items"></app-child>
In your child
@Input()showItemCondition:any
<div *ngFor="let item of items">
{{showItemCondition(item)}}
</div>
Upvotes: 1
Reputation: 31815
You can do it in order to customize the behavior of the ChildComponent
, as long as the callback doesn't have a reference on the parent. In that case, you should refactor your code with an @Output()
.
However, you can't declare a function inside the template so you have to assign it in a variable of the parent and pass that variable to the child. The function should also be declared as a classic function (not arrow), otherwise, this
will refer to the parent.
Upvotes: 0