Yugo Harago
Yugo Harago

Reputation: 341

Arrow function in angular html

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

Answers (3)

StepUp
StepUp

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:

  • it's easier to read
  • you don't have to go to keep going back to the component to see what each function is really doing.
  • using component templates with functions that primarily belongs to classes would result in poor quality code that is hard to maintain.

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:

  • that logic will be placed in different places. You have to go back and forth between template and class.
  • it will harder to maintain to other programmers because they did not expect to have logic in UI. So logic is spread in different places. In my view, it breaks all principles such as SRP. And it makes really hard to maintain code to other future developers
  • even this just one line of code makes code harder to debug

Upvotes: 3

Eliseo
Eliseo

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

Guerric P
Guerric P

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

Related Questions