'How to change mat-icon when i click?
I use mat-menu in Angular and I want to change mat-icon if I click, but things aren't working as I expected. What could I be doing wrong?
This is my app.html:
<button mat-icon-button [matMenuTriggerFor]="menu" >
<mat-icon (click)="changeIcon()">{{icon}}</mat-icon>
</button>
<mat-menu #menu="matMenu" [overlapTrigger]="false">
<button mat-menu-item>
<span>Log in</span>
</button>
<button mat-menu-item>
<span>Register</span>
</button>
</mat-menu>
and my app.ts
export class HeaderComponent implements OnInit {
@ViewChild(MatMenuTrigger) trigger: MatMenuTrigger;
icon = 'more_vert';
constructor() {
}
ngOnInit() {
}
changeIcon() {
if (this.trigger.menuClosed) {
this.icon = 'more_vert';
console.log('fermer');
}
if (this.trigger.menuOpened) {
this.icon = 'close';
console.log('ouvert');
}
}
}
Solution 1:[1]
I found a partial solution. other proposals ?
app.html
<button mat-icon-button [matMenuTriggerFor]="menu" (click)="changeIcon()" #menuTrigger="matMenuTrigger" >
<mat-icon>{{icon}}</mat-icon>
</button>
<mat-menu #menu="matMenu" [overlapTrigger]="false">
<button mat-menu-item>
<span>Log in</span>
</button>
<button mat-menu-item>
<span>Register</span>
</button>
</mat-menu>
and app.ts
import { Component, OnInit, ViewChild, Output, EventEmitter } from '@angular/core';
import { MatMenuTrigger } from '@angular/material/menu';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
@ViewChild(MatMenuTrigger) trigger: MatMenuTrigger;
icon = 'more_vert';
constructor() {
}
ngOnInit() {
}
changeIcon() {
this.trigger.menuClosed.subscribe(() => this.icon = 'more_ver');
this.trigger.menuOpened.subscribe(() => this.icon = 'close');
}
}
Solution 2:[2]
Just thought I'd add this since this entry came up when I was searching for something similar.
You could drop your (click)="changeIcon()" within the markup, and just stick with setting it up in the .TS file (letting your Subscribes do the work):
ngAfterViewInit() {
this.changeIcon();
}
Solution 3:[3]
You could drop your (click)="changeIcon()" within the markup, and just stick with setting it up in the .ts file (letting your Subscribes do the work);
and call in ngonInit();
ngonInit(){
this.changeIcon()
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user9714967 |
| Solution 2 | Rick |
| Solution 3 | Ayush Kumar |
