我定义了一个数组,其中包含将出现在导航栏中的标签和图标名称列表,然后在 html 中,我使用 Angular 材质循环遍历列表以显示所有标签和图标。但如何添加 onclick("logout()") 或 href:'some route'?代码如下,我已将 href 属性添加到 menuItems 表中,但即使使用 {{item.href}} 也可以在 html 中调用它,仅显示不执行操作的文本。
This is Header Component:///////
export class HeaderComponent implements OnInit{
constructor(private userService: UserService) {
}
isLoggedIn: boolean = false;
menuItems: MenuItem[] = [
{
label: 'Offers',
icon: 'notes',
href:'',
showOnMobile: false,
showOnTablet: true,
showOnDesktop: true
}
,
{
label: 'Bookmark',
icon: 'bookmark',
href:'',
showOnMobile: false,
showOnTablet: true,
showOnDesktop: true
},
{
label: 'Application',
icon: 'video_stable',
href:'',
showOnMobile: false,
showOnTablet: false,
showOnDesktop: true
},
{
label: 'Claim',
icon: 'send',
href:'',
showOnMobile: false,
showOnTablet: false,
showOnDesktop: true
},
{
label: 'Forum',
icon: 'forum',
href:'',
showOnMobile: true,
showOnTablet: true,
showOnDesktop: true
},
{
label: 'log out',
icon: 'logout',
href:'click(logout()',
showOnMobile: false,
showOnTablet: false,
showOnDesktop: false
},
{
label: 'Profile',
icon: 'profile',
href:'',
showOnMobile: false,
showOnTablet: false,
showOnDesktop: false
},
];
ngOnInit(): void {
}
logout(){
this.userService.signout()
}
//this is the html :::::
<mat-toolbar fxLayout="row" color="primary">
<span fxFlex><mat-icon>home</mat-icon> Esprit Mobility </span>
<button
mat-button
*ngFor="let item of menuItems"
[fxShow]="item.showOnDesktop"
[fxShow.xs]="item.showOnMobile"
[fxShow.sm]="item.showOnTablet"
>
<mat-icon class="mr">{{item.icon}}</mat-icon>
{{item.label}}
</button>
<ng-container>
<button mat-icon-button [matMenuTriggerFor]="dropMenu">
<mat-icon>more_vert</mat-icon>
</button>
<mat-menu #dropMenu="matMenu">
<ng-container *ngFor="let item of menuItems">
<div
[fxShow]="!item.showOnDesktop"
[fxShow.sm]="!item.showOnTablet"
[fxShow.xs]="!item.showOnMobile"
>
<button mat-menu-item >
<mat-icon class="mr">{{item.icon}}</mat-icon>
{{item.label}}
</button>
<mat-divider></mat-divider>
</div>
</ng-container>
</mat-menu>
</ng-container>
</mat-toolbar>
提前感谢您的帮助:)
.
从视图的角度来看,我会调整按钮。应该指示它触发一个(点击)方法。 if 语句确保 href 不能为空/未定义。
<button mat-menu-item (click)="item.href ? item.href(): ''">
<mat-icon class="mr">{{item.icon}}</mat-icon>
{{item.label}}
</button>
从组件的角度来看,注销对象如下所示:
{
label: 'log out',
icon: 'logout',
href: this.logout,
showOnMobile: false,
showOnTablet: false,
showOnDesktop: false,
},
看一下 href 值 - 它不包含 (),因为它会立即调用函数