[英]Using *ngIf in Angular not working
我是Angular的新手,所以我在嘗試一些我認為很基礎的事情。
我有一個具有以下html的組件:
<div *ngIf="this.showWelcome" class="popup-modal-wrap">
<h3>Hi {{this.currentUser.firstName}}, welcome!</h3>
<a (click)="this.showWelcome = false" class="button naked">Close</a>
</div>
組件本身看起來像這樣:
export class HomeLayoutComponent implements OnInit {
showWelcome = false;
public currentUser: LoggedInUser;
constructor(private userService: UserService, private router: Router) {
}
ngOnInit() {
if (this.router.url == '/welcome') {
this.userService.getCurrentUser()
.subscribe(
currentUser => {
this.currentUser = currentUser;
this.showWelcome = true;
},
error => {
console.log(error);
}
);
}
}
}
此代碼無效,不顯示彈出窗口。 看來,一旦將showWelcome設置為true,它就不會執行任何操作,因為頁面已經呈現。
以下代碼可以正常工作:
if (this.router.url == '/welcome') {
this.showWelcome = true;
}
所以我確定我正在處理某種異步問題
問題是當我從注冊頁面進入時,this.router.url被設置為舊路由,而不是新路由。
測試時,我直接進入/ welcome網址,這就是為什么它起作用的原因
使用* ngIf,this.showWelcome將無法正常工作。 對於數據綁定,您只需在HTML模板中將其作為* ngIf =“ showWelcome”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.