更改 url 时如何路由到另一个组件?

How can I route to another component when changing the url?

我想为应用程序创建一个简单的路由。 我的问题是,当我将 url 更改为 .../myComponent. 组件已呈现,但与 app.component.html 中引用的另一个组件的上下文一起呈现 但是,我喜欢从主要组件“离开”导航到实际组件,因此我只能看到该组件的上下文。

看起来很简单,但是我在这里卡了一会儿,不太明白这个问题。 我认为实现是不正确的,因为在 app.component.html 中使用 router-outlet 它将在这个地方呈现..

    {
        path: 'myComponent', component: myComponent
    },
]

@NgModule({
    RouterModule.forRoot(routes, {initialNavigation: 'enabledBlocking'}),
],
....

app.component.html

<other-selector></other-selector>

<router-outlet></router-outlet>

我的组件

export class MyComponent implements OnInit {

  constructor(private router: Router) { }

  ngOnInit(): void {
      this.router.navigate(['/myComponent']);

  }

} 

所以我的目标只是在将 url 更改为 localhost:..../myComponent

时渲染 myComponent

有人可以告诉我我缺少什么吗?

当您重定向到 myComponent 时,您可以使用 *ngIf 指令来显示和隐藏您的应用程序组件。您需要使用 angular routerEvent 检查请求的 url,您可以根据您的条件将布尔值设置为变量。

app.component.ts

   constructor(router: Router) {
    router.events.forEach((event) => {
      if (event instanceof NavigationStart) {
        this.showOtherComponent = event.url !== '/myComponent';
      }
    });
  }

app.component.html

<app-main-component *ngIf="showOtherComponent"></app-main-component>
<router-outlet></router-outlet>

forked stackblitz

参考:

  1. Angular - RouterEvent