Angular - How to include button event?

122 Views Asked by At

Is there a way to include button in this code which will with click make the same change to an array the same way [ngStyle] does in the following part of the code?

app.component.html

<div class="styling">
  <ul>
    <li *ngFor = "let a of arr"
        [ngStyle]="changeFont()">
        {{a}}
    </li>
  </ul>
</div>

app.component.ts

arr=['car','house','beach','microphone'];
changeFont(){
  return {'font-size.px':15}
}
1

There are 1 best solutions below

2
Eliseo On

In Angular you has variables in .ts, and use this variables in the .html.

An example

style:any=null  //declare a variable

toogleStyle()  //A function that change the variable
{
  if (!this.style)
    this.style={'font-size':'15px';color:'red'}
  else
    this.style=null
}

You can use

<div (click)="toogleStyle()" [ngStyle]="style">click me!</div>

And see how change the style

As you has "severals" <li> you need severals variables if you want severals<li> can be "selected" at time or an unique variable if only one <li> can be selected at time.

  • The "severals variables" are an Array, so to change one element of the array you need pass the "index" of the array

    styles:any[]=[]
    toogleStyle(index:number)  //A function that change the variable
    {
      if (!this.styles[index])
        this.styles[index]={'font-size':'15px';color:'red'}
      else
        this.styles[index]=null
    }
    
     <ul>
        <!--see using let i=index, i becomes value 0,1,2,3...->
        <li *ngFor = "let a of arr;let i=index"
            <!--see you pass the "index" to the function-->
            [ngStyle]="styles[i]" (click)="toogleStyle(i)">
            {{a}}
        </li>
      </ul>
    
  • The unique variable is a number that is the "index" selected. For no selected index, the variable becomes -1 (Remember that 0 is the fisrt element of the array)

    selectedIndex:number=-1
    
    toogleStyle(index:number)  //A function that change the variable
    {
      if (this.selectedIndex==index)  //if you click on selected <li>
        this.selectedIndex=-1;
      else
        this.selectedIndex=index;
    }
    
     <ul>
        <li *ngFor = "let a of arr;let i=index"
            <!--you use the conditional operator (condition)?
                                                value if condition is true:
                                                value if condition is false
            -->
            [ngStyle]="i==selectedIndex?
                          {'font-size':'15px';color:'red'}:
                          null"
            (click)="toogleStyle(i)">
            {{a}}
        </li>
      </ul>