我在Angular中使用mat-menu,如果我点击,我想更改mat-icon,但事情并没有像我预期的那样工作。我能做错什么?
这是我的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>
和我的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');
}
}
}
答案 0 :(得分:0)
我找到了部分解决方案。其他提案?
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>
和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');
}
}
答案 1 :(得分:0)
自从我搜索类似内容时出现此条目以来,我只是想添加一下。
您可以将(click)="changeIcon()"
放在标记中,然后坚持在.TS文件中进行设置(让您的订阅者来完成工作):
ngAfterViewInit() {
this.changeIcon();
}