Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrow function (Lambda function) with Angular 4

I know little about lambda, and lambda expression is treated as a function. and we have lots of ways to do that.

This is my simple function on TypeScript file

 byPan(card1,card2){
    return card1.pan == card2.pan;
 }

which I am using in HTML file like

 <select [compareWith]="byPan" class="form-control" [(ngModel)]="card">
     <option *ngFor="let cardInfo of cards" [ngValue]="cardInfo">{{cardInfo.pan}}</option>
 </select>

If I want to replace this function in lambda then I can write as follows.

var myFunc2 = (card1, card2) => { return card1.pan == card2.pan};  

So my question is, Can I use this lambda function directly on any angular property like compareWith or something like?

 <select [compareWith]="(card1,card2)=> { return card1.pan == card2.pan}" class="form-control" [(ngModel)]="card">
     <option *ngFor="let cardInfo of cards" [ngValue]="cardInfo">{{cardInfo.pan}}</option>
 </select>
like image 268
Vinit Solanki Avatar asked Dec 05 '17 06:12

Vinit Solanki


1 Answers

You can't just execute arrow function in template. Angular will accept only expressions that can bind with component or directives. So basically no, you can't use arrow function in template. It's the best to leave it as a method in your component.

However if you are looking on small expressions you can use shorthand if it could look like:

[compareWith]="card1.pan == card2.pan" // returns bool value

or

[compareWith]="card1.pan == card2.pan ? 'foo' : 'bar".
like image 173
Patryk Brejdak Avatar answered Oct 26 '22 15:10

Patryk Brejdak