用例有点复杂,我不得不求助于Plunker 来演示这个问题。
整个想法是根据窗口的大小实时更改页面的设计。在给定的链接中,如果窗口小于 600 像素,则父模板显示一个 2 列表,当它超过 600 像素时,它显示一个 3 列表中的内容(只是一个示例)。
复制问题的步骤(您也可以在 Plunker 页面中找到它们):
- 打开你的开发者工具
- 点击“打开中间孩子”
- 点击“打开孙子”
- 点击“打开中间孩子”
- 调整预览窗口的大小,如果它小于 600 像素,则将其放大。否则,使其小于 600px(只需更改状态)
- 点击“打开孙子”
错误是:
- 在第 5 步之后,不应显示“孙子”
- 执行步骤 6 将导致您可以在控制台中看到的错误
我相信问题取决于这样一个事实,即有多个,<router-outlet>
并且 Angular 不支持在它们之间切换。我只是希望有办法解决这个问题!
这是app.ts
遵守 SO 的代码:
//our root app component
import { Component, NgModule, VERSION, OnInit, HostListener } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { RouterModule, Router } from '@angular/router';
@Component({
selector: 'my-app',
template: `
<div (window:resize)="onResize($event)" style="width: 100%; height: 100%">
Steps to replicate the problem:
<ol>
<li>Open your developer tools</li>
<li>Click on "Open middle child"</li>
<li>Click on "Open grand child"</li>
<li>Click on "Open middle child"</li>
<li>Resize the preview window in a way that if it was less than 600px, make it larger. Otherwise, make it smaller than 600px (just change the state)</li>
<li>Click on "Open grand child"</li>
</ol>
Notes:
<ul>
<li>After step 5, the "Grand child" should have not been shown</li>
<li>Following step 6 will result in an error that you can see in console</li>
</ul>
<table *ngIf="columns == 2" class="frame">
<tr>
<td colspan="2">2-Column design - "{{router.routerState.snapshot.url}}"</td>
</tr>
<tr>
<td><a [routerLink]="['/middle-child']">Open middle child</a></td>
<td><router-outlet></router-outlet></td>
</tr>
</table>
<table *ngIf="columns == 3" class="frame">
<tr>
<td colspan="3">3-Column design - "{{router.routerState.snapshot.url}}"</td>
</tr>
<tr>
<td><a [routerLink]="['/middle-child']">Open middle child</a></td>
<td><router-outlet></router-outlet></td>
<td>3rd column</td>
</tr>
</table>
</div>
`,
})
export class App implements OnInit {
name:string;
columns: number = 2;
constructor(private router: Router) {
this.name = `Angular! v${VERSION.full}`
}
ngOnInit() {
this.columns = window.innerWidth < 600 ? 2 : 3;
}
@HostListener('window:resize', ['$event'])
onResize(event) {
this.columns = event.target.innerWidth < 600 ? 2 : 3;
}
}
@Component({
template: `
<table>
<tr><td>Middle child here</td></tr>
<tr><td><a [routerLink]="['/middle-child/grand-child']">Open grand child</a></td></tr>
<tr><td><router-outlet></router-outlet></td></tr>
</table>
`
})
export class MiddleChild {}
@Component({
template: `Grand child`
})
export class GrandChild {}
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot([
{ path: 'middle-child', component: MiddleChild, children: [
{ path: 'grand-child', component: GrandChild }
] }
])
],
declarations: [ App, MiddleChild, GrandChild ],
bootstrap: [ App ]
})
export class AppModule {}