0

I have the following JSON object:

{Countries: [America, China, Russia, etc]}

I have a function defined in my countries.component.ts(typescript) component file for EACH country:

...
America() { ... }
China() { ... }
Russia() { ... }
etc

Suppose I have a ngFor in my component template that iterates over the JSON object.I want to be able to bind a click event in such a way:

<ul *ngFor="let country of Countries">
  <li>
    <a (click)="{{country}}()" >{{country}}</a>
  </li>
</ul>

when I click on the "America" anchor element it will invoke the "America()" function.

Is there a way to bind a click event to a dynamic function name (even though the functions are statically defined in the appropriate component class (ie. America, China, Russia, etc are defined) ?

Thanks in advance for your responses.

1 Answer 1

1

Interpolation doesn't seem to work the way you tried. A possible solution to your problem is to give arguments to the function in *ngFor.

code:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `


  <ul *ngFor="let x of countries">
  <li>
    <a (click)="doThis(x)" >{{x}}</a>
  </li>
</ul>

  `
})
export class AppComponent {
  constructor(){console.clear()}



  public countries:any[]= ['America','China', 'Russia', 'Germany']



  doThis(x){


    console.log('life is life in '+ x)
  }



}

Plunker

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.