Conceal elements depending on the route path in Angular versions 5 and 6

I'm currently overseeing a project in Angular and I encountered an interesting obstacle when attempting to enhance the system. There are certain elements that should not be visible on specific URLs.

Is there a method to conceal an element based on the URL in Angular 5 or 6?

I am eager to learn about the most effective approach to accomplish this task.

For instance, domain.com/home, domain.com/package, among others.

Answer №1

When working with Angular, we tend to create fewer directives since components can handle most cases. However, there are still situations where creating a directive is necessary :).

1 - Creating a Directive and Injecting the Router:

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

 @Input() url : string;

 constructor(private router: Router){
   router.events.subscribe( (event) => {
     // You can observe the route changes here :)
   });
 }

With this setup, you will be able to track which route you are currently on.

2 - Time to Decide Whether to Hide or Display:

You can also utilize TemplateRef and ViewContainerRef to manipulate the DOM.

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

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

3 - Wrapping It Up:

    if (this.url // Show content on correct URL) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }

4 - Simply attach this directive to the element you wish to control.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What processes occur behind the scenes when DownGit downloads specific files or folders from GitHub?

I was looking for a way to download specific files or folders from GitHub and discovered DownGit. However, I am curious about the inner workings of this tool. After reading the README.md on https://github.com/MinhasKamal/DownGit, I still couldn't ful ...

Angular Service Worker: 504 error encountered during application deployment refresh

After building my Angular 8 project with ng build --prod, I serve it from the /dist folder using http-server. The app still works even after stopping it thanks to the service worker. The project successfully registers its service worker and I am able to ...

What is the best way to add a custom class alongside cdk-overlay-pane for a material menu in Angular 7?

I have a specific requirement to create a mega menu using Angular Material Menu. I attempted to apply some custom styling to the cdk-overlay-pane using my own class, but it did not work as expected. I tried to add a custom class to the mat-menu element us ...

What is the best way to access data in a node.js application from IONIC typescript via a REST API?

Here is the structure of my service.ts: import { Injectable } from '@angular/core'; import {Http, Headers} from '@angular/http'; import 'rxjs/add/operator/map'; /* Generated class for the PeopleSearch provider. See http ...

How to eliminate parameters from the URL in Ionic 2 with Angular 2

Basically, in my application, when a user receives an email notification with a hyperlink to open a specific record based on an ID number, the URL looks like this: https://myappserver.com/?aid=12343551 So, after the user opens the record, I'm wonder ...

The installation process resulted in the failure of loading the Ionic plugin

After creating an app with Ionic, I encountered an error when installing a plugin core.js:1449 ERROR TypeError: Object(...) is not a function at AppRate.set [as preferences] (index.js:31) at MyApp.webpackJsonp.259.MyApp.initializeApp (app.componen ...

Issue displaying values in select option tag

My issue lies in initializing a select dropdown with static values for male and female. When I try to use ngFor to dynamically populate the options, nothing appears: component.ts: export class MemberListComponent implements OnInit { user: User = JSON.pa ...

The input elements are failing to show up in the form as variables

When developing my Angular chat application, I faced an issue where a new message component was created every time a message was received. Here is the code snippet I used: feedComponent.html <app-message *ngFor="let message of chatMessages" [ChatMessa ...

If the table spans multiple pages, a top margin will be added to ensure proper formatting. This feature is implemented using jspdf-autotable

I have encountered an issue with my PDF function where using multiple tables and the didDrawPage() hook to add headers and footers results in images being drawn multiple times in the header due to the multiple tables. To resolve this, I created a separate ...

NGRX Angular does not support iteration of state.data

I'm attempting to combine state.data with payload.data but encountering an error: TypeError: state.data is not iterable This is my code snippet: on(apiActionGroup.success, (state, payload) => newState(state, { data: { [payload.page?.toStrin ...

The data type 'Observable<{}[]>' cannot be matched with the type 'AngularFireList<any>'

I have been learning how to use AngularFire2 by following this tutorial. Encountered the error: 'Type 'Observable<{}[]>' is not assignable to type 'AngularFireList'. Property 'query' is missing in type 'Obse ...

In Typescript, object properties make assertions about other properties within the object

I have a specific object that I use to store data received from an API. This object is structured as follows: class Storage { isReady: boolean = false; content: object || null = null; } I have noticed that when isReady is false, content is null. Con ...

Error in TypeScript: The type 'Color' cannot be assigned to the type '"default" | "primary" | "secondary"'

Currently, I am utilizing MUI along with typescript and encountering the following issue. It seems like I may be overlooking a fundamental concept here but unfortunately cannot pinpoint it. Error: Type 'Color' is not assignable to type '&quo ...

What is the rationale behind Typescript permitting the assignment of an "any" object type to a class object?

Within my codebase, there is a class object that I have initialized: groupNameData: GroupNameData = new GroupNameData(); In addition, I also have an any object called groupNameDatas. groupNameDatas: any; Experiment 1 (class = any) To experiment with ...

Developing a structure or definition for a Map

Currently, I have created a type and interface in TypeScript to explicitly define the things variable and the Map constructor call. type Things = Map<string, ThingValue>; interface ThingValue { label: string; count: number; } const things: Thi ...

Hosting static files in .NET Core 3.1

I am encountering an issue with my app built on .Net Core 3.1 and Angular 10. Within my Startup.cs file, I have the following code snippet: app.UseStaticFiles(); app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(Path. ...

Typescript: Establishing a class method with parameters that are inherent to the class

After creating a class, I realized that there is repeated logic that can be extracted into a method on the class to be reused by other properties of the class. class Card { protected readonly data: Data; protected readonly user: User; nameVal: strin ...

In React Typescript, there is an issue with react-router v4 where the Route component does not pass its props to the specified component

Struggling with React Router v4 and history usage in Browserrouter. Whenever attempting to access this.props.history.push("/"), the error pops up: TS2339: Property 'history' does not exist on type 'Readonly<{ children?: ReactNode; }> ...

My project in WebStorm encounters a setback due to the updated release of Typescript 5+

Recently, I had to upgrade my TypeScript version from 4.9.5 to 5.1.3 because one of the libraries I'm using made a fix that required a newer TypeScript version. After the update, TypeScript started throwing errors for console calls and React event di ...

A step-by-step guide on reversing options in the Ant Design Cascader component

By default, the Cascader component's options are nested from left to right. I am looking to have them go from right to left instead. However, I could not find anything in the component's API that allows for this customization. Is it even possibl ...