Conceal specific elements across various paths in Angular 5

Attempting to hide a component based on matching routes, it is currently working with one route but not with multiple routes.

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

@Component({
    selector: 'app-root',
    template:  `
    <app-header *ngIf="!_router.url.includes('account', 'admin', 'app')"></app-header>
    <router-outlet></router-outlet>
    <app-footer *ngIf="!_router.url.includes('app', 'account', 'admin')"></app-footer>
`
})
export class RootComponent {
    router: string;

    constructor(
        public _router: Router
    ) {
        this.router = _router.url;
    }
}

The current implementation does not work for multiple words in the includes() function. Is there an alternative method to achieve this?

edit

I have attempted the following...

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

@Component({
    selector: 'app-root',
    template:  `
        <app-header *ngIf="!hasMatches('app', 'account', 'admin')"></app-header>
        <router-outlet></router-outlet>
        <app-footer *ngIf="!hasMatches('account', 'admin', 'app')"></app-footer>
    `
})
export class RootComponent {
    router: string;

    constructor(
        public _router: Router
    ) {
        this.hasMatches();
        this.router = _router.url;
    }

    private hasMatches(...values: string[]): boolean {
        let matchFound = false;

        for (let i = 0; i < values.length; i++) {
            if (this.router.indexOf(values[i]) > -1) {
                matchFound = true;
                break;
            }
        }

        return matchFound;
    }
}

Thank you!

Answer №1

Utilize the indexOf() function. The hasMatches()-method presented below is designed to handle multiple arguments as needed.

HTML

<app-header *ngIf="!hasMatches('account', 'admin', 'app')"></app-header>
<router-outlet></router-outlet>
<app-footer *ngIf="!hasMatches('app', 'account', 'admin')"></app-footer>

TS

routeUrl: string;

constructor(
    public _router: Router
) {
    // Subscribe to router events to constantly update the current URL
    this._router.events.subscribe(() => this.routeUrl = this._router.url ); 
}

private hasMatches(...values: string[]): boolean {
    let matchFound: boolean = false;

    // Check for null or undefined values first
    if(this.routeUrl){ 
        for (i=0; i<values.length; i++){
             if(this.routeUrl.indexOf(values[i]) > -1){
                matchFound = true;
                break;
             }
        }        
    }

    return matchFound;
}

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

Injecting shared libraries in a NestJs monorepo system

I am working on a NestJS application that consists of several microservices stored in a single repository following the monorepo approach. The AccessControl module is located in the libs directory and is meant to be shared across multiple microservices. I ...

Rendering the HTML5 canvas within a console environment

I am looking to create images of humans on the console using nodejs. In order to achieve images of higher quality, I require a library or module that can facilitate drawing images in the console. Some options available include imaging and console-png. How ...

Is there a way to make the scrollbar-react component extend to full page width?

I'm currently in the process of developing a to-do application that consists of a sidebar and a page for listing tasks. My goal is to have the page fill the entire screen without specifying a fixed height. Would it be feasible to achieve this using s ...

Unlocking the potential: Clicking on all ng-if elements with matching text using Chrome console

I am currently trying to determine how to automatically click on all elements that have a specific state. The page appears to be built using Angular, although I am unsure of the exact version being used. My approach involves using the console in Chrome t ...

Is it possible for my Angular application to have dual Firebase configurations?

I need to switch between 2 databases from different Firebase apps that I have created. Utilizing Angular version 7 and AngularFireModule for configuration initialization. The goal is to toggle between firebaseAdmin and firebaseProd. My attempt at initia ...

Locate the specific version of a JavaScript library within compiled JS files

The dist folder houses the results of running npm install. If I don't have access to the original package.json file used during the compilation of the distributable, how can I determine the version of a particular library that was utilized in the ins ...

Refresh a table using jQuery Mobile, PHP, and AJAX without having to reload the entire page by clicking a

Currently, I am working on a web app that includes a pop-up feature. When the user clicks on the pop-up to close it, I want the table data to refresh without having to reload the entire page. This pop-up allows users to modify existing data in the table. A ...

PHP implementation that enables multi-threaded ajax calls

I'm working on developing a web app that can detect stock availability for one or multiple e-commerce items based on the URLs inputted by the user. These URLs can be separated by commas. Currently, I am making AJAX calls to one of my PHP scripts for e ...

Creating conditional observable debounceTime

I've implemented a basic debounce on an input element event in the following way: Observable .fromEvent(this.elInput.nativeElement, 'input') .debounceTime(2000) .subscribe(event => this.onInput(event)); Is there ...

The <form> element is giving me headaches in my JavaScript code

Trying to troubleshoot why my HTML pages render twice when I add a form with JavaScript. It seems like the page displays once with the script and again without it. Below is the basic HTML code: <form action="test.php" method="post"> <div class=" ...

What happens if I don't associate a function or method in the React class component?

Take a look at this straightforward code snippet that updates a count using two buttons with different values. import "./App.css"; import React, { Component } from "react"; class App extends React.Component { // Initializing state ...

I attempted to create a test scenario to verify that the length of the tasks array is not negative. However, when trying to test this using 'not.toBe' in the code below, an error was encountered

app.js var todos=[]; todos=['to-do one', 'to-do two']; module.exports=todos; app.test.js const todos=require('./app') test('should have a length of at least 0',()=>{ expect(todos.length).toBeGreaterThanOrEqu ...

Incorrect information being transmitted and shown

I'm facing an issue with my JavaScript code and despite numerous attempts, I'm unable to resolve it on my own due to being a beginner in JavaScript. The problem revolves around displaying a hidden message upon submitting the page without filling ...

Is there a way to click on a button and have its background color change randomly each time?

I am facing an issue with a button on my HTML page. When the button is clicked, I want its background color to change to a random different color. However, despite trying various sources, I am unable to get it right. It seems like I am not placing the code ...

CSS animation fails to animate the object

I am encountering an issue with a CSS animation that I am trying to implement for each child within a nav element. Specifically, I am attempting to create a dynamic stock panel. Interestingly, when I add another CSS attribute like color, it works as expec ...

Adding graphs dynamically to Dygraphs allows for real-time updates and interactive data

I recently started using Dygraphs for one of my projects and I am still learning how to work with it. After reading through the documentation and looking at a few examples, I noticed that the constructor for Dygraphs requires a div element where the graph ...

Utilizing JSONLoader to load several models simultaneously

Seeking advice on the most effective method for loading multiple models exported from Blender to JSON format. In the provided example below, I am utilizing the static_objects array containing predefined object data and model URLs. These URLs are then iter ...

Prevent a <span> element from affecting the linking functionality of an <a> tag

Is it possible to make a hyperlink clickable without including the <span> tags within it and instead attaching a jQuery event to those tags? This is the code I'm using. It utilizes bootstrap's list-group for a navigation element: <ul cl ...

IE Compatibility with CSS 3 Text Shadow

Currently, I am implementing a CSS 3 text shadow to mimic a bevel and emboss effect on my web application. Unfortunately, when viewed on IE 10, the shadow appears distorted which is quite frustrating. I have not yet tested it on IE 9. Is there a solution t ...

Dependency management in ReactJS components

I am grappling with the optimal structure for a React component that is composed of other components. Let's look at the first example: <ColorSelect id="color" label={this.state.selectLabel} trigger={{ color: "lime", text: "Lime"}} onPropagateCli ...