【发布时间】:2020-11-07 23:15:42
【问题描述】:
我正在使用 Angular 9,我想在用户登录时动态更改菜单项的数据。但是,由于菜单与主页一起加载,因此当用户登录时,数据会更改在我手动刷新页面之前不会反映在菜单项中。我尝试使用 Renderer 2、ChangeDetectorRef 和 ElementRef,但未能自动重新加载菜单。下面我只添加相关元素,因为实际的组件代码很长。询问我是否需要了解其他信息:
HTML:
<div class="widget-text">
<a mat-button [matMenuTriggerFor]="accountMenu" #accountMenuTrigger="matMenuTrigger" *ngIf="!isLoggedIn">
<mat-icon>person</mat-icon>
<span fxShow="false" fxShow.gt-sm class="flag-menu-title">Account</span>
<mat-icon class="mat-icon-sm caret cur-icon">arrow_drop_down</mat-icon>
</a>
<mat-menu #accountMenu="matMenu" [overlapTrigger]="false" xPosition="before" class="app-dropdown">
<span>
<button mat-menu-item [routerLink]="['/admin/login']" routerLinkActive="router-link-active">
<mat-icon >person</mat-icon>
<span>Login</span>
</button>
<button mat-menu-item [routerLink]="['/admin/login']" routerLinkActive="router-link-active">
<mat-icon>person_add</mat-icon>
<span>Register</span>
</button>
</span>
</mat-menu>
<a mat-button [matMenuTriggerFor]="profileMenu" #profileMenuTrigger="matMenuTrigger" *ngIf="isLoggedIn">
<mat-icon>person</mat-icon>
<span fxShow="false" fxShow.gt-sm class="flag-menu-title">Howdy, {{name}}</span>
<mat-icon class="mat-icon-sm caret cur-icon">arrow_drop_down</mat-icon>
</a>
<mat-menu #profileMenu="matMenu" [overlapTrigger]="false" xPosition="before" class="app-dropdown">
<span>
<button mat-menu-item [routerLink]="['/admin/profile']" routerLinkActive="router-link-active">
<mat-icon >person</mat-icon>
<span>Profile</span>
</button>
<button mat-menu-item (click)="logout()">
<mat-icon>warning</mat-icon>
<span>Logout</span>
</button>
</span>
</mat-menu>
</div>
打字稿:
public name;
public isLoggedIn = false;
constructor(public router: Router, private cartService: CartService, public sidenavMenuService:SidebarMenuService) {
this.checkLogin();
this.name = Cookie.get('userName');
}
public checkLogin(): any {
if(Cookie.get('authtoken')) {
this.isLoggedIn = true;
}
}
【问题讨论】:
-
您要更改的模板中的菜单项是什么?
-
将
constructor中的任何代码移至ngOnInit或ngOnChange。 -
@Charlie 如果变量 isLoggedIn = true 那么垫子按钮应该从 Account 更改为 Howdy, {{name}}
-
@Benny 没有改变任何东西
-
您的
checklogin函数在构造函数中。它应该在您的登录代码之后立即执行..
标签: javascript angular typescript angular-material angular-changedetection