【问题标题】:Hide element based on the route path in Angular 5,6根据 Angular 5,6 中的路由路径隐藏元素
【发布时间】:2018-09-24 20:11:47
【问题描述】:

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

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

我想了解实现这一目标的最佳体验。

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

【问题讨论】:

  • 基于window.location.path之类的页面元素?
  • @AustinTFrench,我的意思是角度路由,例如,当路由是 /home 和 /package 等时,我想隐藏元素。

标签: angular typescript frontend


【解决方案1】:

在 Angular 中,我们通常创建越来越少的指令,因为组件英尺占案例的 90%。但这是您需要创建一个的典型情况:)。

1 - 创建指令并注入路由器:

 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 - 您只需在要管理的元素上添加此指令

【讨论】:

    猜你喜欢
    • 2017-05-21
    • 1970-01-01
    • 2018-05-24
    • 2021-03-10
    • 1970-01-01
    • 2013-04-17
    • 1970-01-01
    • 2016-09-16
    • 2019-07-12
    相关资源
    最近更新 更多