Search code examples
javascriptarraysangulartypescriptngfor

Change array from button inside *ngFor


I have 3 buttons with let link of links

links = [
    {
      name: "Link 1",
      id: "number1"
    },
    {
      name: 'Link 2',
      id: "number2"
    }
    {
      name: "Link 3",
      id: "number3"
    }
  ]

They render 3 button in HTML.

I have a DIV with "let card of number1":

number1 = [
    {
      name: 'IT',
      address: 'Tokyo 4',
    },
    {
      name: 'Computer',
      address: 'Tokyo 4',
    },
    {
      name: 'Garden',
      address: 'Tokyo 4',
    },
    {
      name: 'Cars',
      address: 'Tokyo 4',
    }
  ]

And they render DIV with H1 {{ card.name }} and P with {{ card.address }}

But, how change let card of number1 to let card of number2 when I click on the button number 2? Like this:

(click)="change number1 to number2" - when I click button number 2 etc

PLUNKER: https://plnkr.co/edit/MfSx9MjoVtHprFtBHKDZ?p=preview


Solution

  • An other approach:

    HTML:

     <li *ngFor="let link of links; let i = index">
          <button (click)="setNumber(i)">{{ link.name }}</button>
     </li>
    

    Typescript:

    ...
    number;
    ....
    constructor(){
        this.number=this.number1
    }
    
    ...
    setNumber(index){
      console.log(index)
      switch(index){
        case 0:
          this.number = this.number1;
          break;
        case 1:
          this.number = this.number2;
          break;
        case 2:
          this.number = this.number3
      }
    }
    

    DEMO