Angular 子路由观察者

Angular child route observer

在 Angular5 应用程序中,我的路由定义如下:

path: 'my-object/:id',
    component: MyObjectDetailComponent,
    children: [
        {path: '', redirectTo: 'sublist', pathMatch: 'full'},
        {path: 'sublist', component: PointComponent},
        {path: 'new', component: PointFormComponent},
    ],

在 MyObjectDetailComponent 模板文件中我有:

<button #new />
<router-outlet></router-outlet>

当我向用户显示 PointForm 时,我需要隐藏一些界面对象(例如新按钮)。

我认为我需要向 url 或路线添加某种观察者 - 但不知道如何(以及在​​哪里)。

它应该在用户输入 PointFormComponent(路径:新)时隐藏 <button #new />(和其他一些 UI 元素)并在他离开时再次显示它们。

您可以在 MyObjectDetailComponent 中添加类似这样的内容:

import { Router } from '@angular/router';

export class MyObjectDetailComponent implements OnInit {

    currentUrl: string;

    constructor(private router:Router) {  }

    ngOnInit() {
        // that´s how you get the current url
        currentUrl = this.router.url; 
    }
}

并在您的模板中添加类似的内容

<button *ngIf="currentUrl == ![add path to "new" url here]" #new />
<router-outlet></router-outlet>

你需要这样做,这意味着你需要检查路由更改,如果更改的路由中包含新的,则将 hideflag 设置为 true 并隐藏 contorls

class MyClass {
  hideInputs = false;
  constructor(private router: Router) {
    router.events.subscribe((val) => {
      const href = window.location.href;
       this.hideInputs = href.endsWith('/new');
    });
  }
}


<button *ngIf="hideInputs " #new />