angular - 如何在我的其他组件中排除 app.component.html 的代码

标签 angular typescript

app.component.html 是我们的默认组件,其中添加了一个菜单,但我不想将它包含在我的其他组件中。

我该怎么做?

问题是当我加载 newsection.component.html 时,它在顶部显示了 app.component.html,如下所示:

enter image description here

如何限制它,使其不会加载到 editsection.component.html 之上?

最佳答案

您可以结合 Dhyey 和 Hamed Baatour 的回答。

首先,为您的菜单创建一个单独的组件(例如 menu.component.ts)并将所有代码放入其中。

然后修改你的app.component.ts,让它看起来像这样:

<menu-component *ngIf="showMenu"></menu-component>
<router-outlet></router-outlet>

重要:现在您必须在 app.component.ts 中设置 showMenu在您的 newsection.component.ts 中。

您可以通过检查请求的 URL 来完成此操作。只需像这样在 app.component.ts 中注入(inject)路由器:

constructor(router:Router) {
router.events.forEach((event) => {
    if(event instanceof NavigationStart) {
        this.showMenu = event.url !== "/newsection";
    }
  });
}

如果请求带有 /newsection 的路由,这不应该显示菜单。

关于angular - 如何在我的其他组件中排除 app.component.html 的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44845770/

相关文章:

javascript - Angular 6 - router-outlet - 使用 CSS 加载外部 HTML

javascript - 将 typescript 的 .map 文件输出到 IntelliJ IDEA 中的特定文件夹

typescript - 混合接口(interface)中的类型检查

typescript :联合类型到可选值的深度交集(难度:95+)

Angular-cli Karma 测试不适用于新项目

库中的 Angular 默认管道不起作用

apache - 如何为 Angular 2 配置 Apache

json - 在 typescript 中为 JSON 文件添加类型定义

node.js - 无法在同一个 TypeScript 项目中使用 requireJS 和 Node 的 Require

Angular 4 新的 HttpClient 内容配置 header