当我的组件从服务获取登录用户时,我试图触发一个事件,因为我只想在用户登录时显示导航栏。
这是我的 app.component 代码:
import { Component, OnInit, EventEmitter, Input, Output } from '@angular/core';
import { ROUTER_DIRECTIVES, Router } from '@angular/router';
import { LoginComponent } from './login.component';
import { DashboardComponent } from './dashboard.component';
import { ControlDetailComponent } from './control-detail.component';
import { PageNotFoundComponent } from './pagenotfound.component';
import { SettingsComponent } from './settings.component';
import { UserService } from '../service/user.service';
import { User } from '../object/user';
@Component({
selector: 'myApp',
templateUrl: './app/template/app.component.html',
styleUrls: ['styles.css'],
directives: [ROUTER_DIRECTIVES],
precompile: [LoginComponent, DashboardComponent, ControlDetailComponent, PageNotFoundComponent, SettingsComponent]
})
export class AppComponent {
@Input() loggedUser:User;
@Output() userChanged:EventEmitter<User> = new EventEmitter<User>();
constructor(private _userService:UserService, private _router:Router) {}
ngAfterViewInit() {
if(this._userService.isUserLogged()) {
this.userChanged.emit(this._userService.loggedUser);
}
}
switchUser(event) {
this.loggedUser = event.target.value;
console.log("event triggered");
}
}
这是它的相关模板:
<div class="all-content">
<nav (userChanged)="switchUser($event)" *ngIf="loggedUser">
<ul>
<a [routerLink]="['/dashboard']" routerLinkActive="active">Dashboard</a>
<a [routerLink]="['/settings']" routerLinkActive="active">Settings</a>
<a (click)="logout()">Logout</a>
</ul>
</nav>
有人知道为什么我的事件没有被触发吗?
最初我认为问题是*ngIf
阻止触发事件的指令,但是即使删除它,事件也不会被触发......