showing results for - "change icon on click angular"
Clotilde
28 Jun 2020
1import { Component } from '@angular/core'
2
3export interface CollapsibleItem { 
4    label: string; 
5    text: string;
6    state: boolean;
7}
8
9@Component({
10selector:'whateveryouwant',
11template: `
12
13<ul class="collapsible" data-collapsible="accordion">
14    <li *ngFor="let item of menuItems; let i = index" (click)="menuClick(i)">
15       <div class="collapsible-header">
16         <i class="material-icons" *ngIf="item.state"> minus-icon </i>
17         <i class="material-icons" *ngIf="!item.state"> plus-icon </i>
18         {{ item.label }} 
19       </div>
20       <div class="collapsible-body">
21         <span> {{ item.text }} </span>
22       </div>
23    </li>
24`,
25styles: ['']  
26})
27
28export class YourComponentName {
29
30   constructor() {  }  
31
32    menuItems: CollapsibleItem[] = [
33    { label: 'First', text: 'Lorem Ipsum', state: false },
34    { label: 'Second', text: 'Lorem Ipsum', state: false },
35    { label: 'Third', text: 'Lorem Ipsum', state: false },
36   ];
37
38    menuClick(clickedItem: number) {
39        this.menuItems[clickedItem].state = !this.menuItems[clickedItem].state  // flips the boolean value for the clicked item 
40        for (let item of this.menuItems) {  
41           if ( item !== this.menuItems[clickedItem] ) { 
42               item.state = false; 
43           }
44        }
45        // the for loop goes through the array and sets each item to false *if* its not the item that was clicked
46     }   
47 }
48