Angular 2 TypeScript functions with return value and binding it to HTML

3.6k views Asked by At

I am a beginner with Angular and TypeScript and I have a function like

jajal(varname:string) {
  switch (varname) {
    case "foo":
      varname = "foo-return"
      break;
    case "bar":
      varname = "bar-return"
      break;
    case "ok":
      varname = "ok-return"
      break;    

    default:
      varname="not processed"
      break;
}

and the HTML template like

<ion-item button class="item item-icon-left item-icon-right" *ngFor="let user of users">
  <p>jajal({{user.icon}})</p>
  <h2>{{user.icon}}</h2>
  <ion-icon name="arrow-forward" item-right></ion-icon>
</ion-item>

(this is an Ionic project).

I just wanna sent the user.icon value from HTML (p element) template to the jajal() function and get return value but it doesn't work.

1

There are 1 answers

0
YugoAmaryl On

Looks like what you need is a pipe. you can define a customer pipe like this

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'jajal'})
export class JajalPipe implements PipeTransform {
  transform(varname: string): string {
    switch (varname) {
      case "foo":
        varname = "foo-return"
        break;
      case "bar":
        varname = "bar-return"
        break;
      case "ok":
        varname = "ok-return"
        break;    

      default:
        varname="not processed"
        break;
    }

    return varname;
  }
}

And use it in your template like this

{{user.icon | jajal}}

Wish this would help. And you'd better check the doc first, you will find it useful, https://angular.io/docs/ts/latest/guide/pipes.html