一個解決方案可能是將UsersComponent
模板中的所有內容都簡單地包裹起來,除了div
中的router outlet
之外。如果組件有孩子(UsersEditComponent
在這種情況下),則相應地隱藏/顯示div
。
這樣做可以讓您的路由器在UsersComponent
和UsersEditComponent
之間保持正確的父級/子級別,但仍然只在激活路由時顯示UsersEditComponent
內容。
這是正是這麼做的UsersComponent
實現:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
@Component({
template:
`<div *ngIf="!hasChildren">
User 1 <button md-icon-button (click)="editUser(1)">edit</button><br/>
User 2 <button md-icon-button (click)="editUser(2)">edit</button>
</div>
<router-outlet></router-outlet>
`
})
export class UsersComponent implements OnInit {
private hasChildren: bool;
constructor(private router: Router, private route:ActivatedRoute) { }
editUser(id) {
this.router.navigate(['users/edit', id]);
}
ngOnInit() {
this.hasChildren = false;
this.router.events.filter(event => event instanceof NavigationEnd).subscribe(event => {
this.hasChildren = this.route.children.length > 0;
}
}
}
很不錯的,你加了plunkr,試圖幫助了:) –