首页 > 解决方案 > 根据 Angular 5,6 中的路由路径隐藏元素

问题描述

我现在正在管理一个 Angular 项目,在尝试改进系统时遇到了一件奇怪的事情。某些元素不应显示在某些 url 上。

有没有办法根据 Angular 5 或 6 中的 url 隐藏元素?

我想知道实现这一目标的最佳体验。

例如 domain.com/ home、 domain.com/ package等。

标签: angulartypescriptfrontend

解决方案


在角度方面,我们通常会创建越来越少的指令,因为组件脚占案例的 90%。但这是您需要创建一个的典型情况:)。

1 - 创建一个指令 en 注入路由器:

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

 @Input() url : string;

 constructore(private router: Router){
   router.events.subscribe( (event) => {
     // I think you can see the route change here :)
   });
 }

从这里您将能够知道您在哪条路线上。

2 - 现在隐藏与否?

你也可以注入 templateRef 和 containerRef 来玩 DOM。

 import { Directive, TemplateRef, ViewContainerRef } from '@angular/core';

 constructore(private route: Router,
              private templateRef: TemplateRef<any>,
              private viewContainer: ViewContainerRef){
 }

3 - 完成:

    if (this.url // On a good URL show the content) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }

4 - 您只需在要管理的元素上添加此指令


推荐阅读