Angular - Implementing *ngIf based on URL parameters

Is it possible to display an element based on specific queryParams included in the URL?

For example:

ngOnInit() {
    this.route.queryParams.subscribe(params => {
        console.log(params);
    });
}

If I want to achieve something similar to this:

<div *ngIf="queryParams = 'query_name'"></div>

Answer №1

To utilize a specific query parameter in a condition, you must first assign it to a property and then reference that property within the *ngIf directive.

queryParameter;

ngOnInit() {
    this.route.queryParams.subscribe(params => {
        this.queryParam = params['yourParamName'];
    });
}

In your HTML markup:

<div *ngIf="queryParam == 'yourCondition'"></div>

Answer №2

When working in a .ts file, you can set up query parameters like this:

private queryParams:string ='';

ngOnInit() {
    this.route.queryParams.subscribe(params => {
        this.queryParams= params['parameterName'];

    });
}

To clarify, if the route is "/userId" the code should look like this:

this.queryParams= params['userId'];

When working in a .html file, you can use the following code snippet to check for specific query parameter values:

<div *ngIf="queryParams.toLowerCase() === 'queryName'.toLowerCase()"></div>

For example, if the intended string is "userName," the code would look like this:

 <div *ngIf="queryParams.toLowerCase() === 'userName'.toLowerCase()"></div>

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

Issue with OpenAI's Rate Limit 429 Restriction

I've been experimenting with this repository in order to implement semantic search for YouTube videos using OpenAI + Pinecone. However, I keep encountering a 429 error at the following step - "Run the command npx tsx src/bin/process-yt-playlist.ts to ...

NGRX reducer avoids generating errors due to incorrect assignments

My experience with ngrx is relatively new. In my typical TypeScript work, I usually encounter an incorrect assignment error like the one below due to a missing property in the interface declaration: interface IExample { count: number; } let initialState ...

Implementing Class-based Dependency Injection in Express

Incorporating Express into a TypeScript project has presented me with a particular scenario Here is my route file: ... import findAllUsersFactory from "src/factory/FindAllUsers"; routes.get("/users", findAllUsersFactory().handle); ... ...

Transferring data to a different module

I'm currently working on an Angular program where I am taking a user's input of a zip code and sending it to a function that then calls an API to convert it into latitude and longitude coordinates. Here is a snippet of the code: home.component.h ...

The ReferenceError occurs exclusively during the execution of tests

I keep encountering a dull stacktrace after executing my test. I've experimented with solutions like using fakeTimers, require('iconv-lite')..., etc, based on these queries: Encoding not recognized in jest.js ReferenceError: You are trying ...

Where can I locate the scss file declarations in a Nativescript drawer navigation template?

I have customized my app using the nativescript drawer navigation template. Everything was working fine until I incorporated a login page. Now, I am encountering an error related to the "$page-icon-color" variable in the sass-loader plugin. The styling ...

I encountered a TypeScript error in React Native when attempting to use "className" with TypeScript

Although I've been using React for a while, React Native is new to me. I recently started using tailwind with import { View, Text } from "react-native"; import React from "react"; export default function Navigation() { return ...

Having trouble reaching the unidentified function

There are two different scenarios where the 3rd party library (BrowserPrint.js) is used; FUNCTIONAL ENV - JS and jQuery with the 3rd party libraries included simply in the <head> section of the document and the main function being called in $(do ...

Union does not contain the specified property in Typescript

Here are the types that I have: Foo { foobar: any } Bar { fooBarBar: any; } I want to use a function defined like this: this.api.submit(param: Foo | Bar) When trying to use it, I encountered an issue: this.api.submit(param.foobar) // does no ...

Guide to organizing the table according to the values (timestamps) in a specific column

In one of the tables I'm working with, there is a column called uploadedOn. You can see it in action here: https://stackblitz.com/edit/angular-ivy-tntvst?devToolsHeight=33&file=src/app/app.component.ts 1: https://i.stack.imgur.com/aQ6wh.png. My g ...

Executing various angular 4 applications simultaneously using a shared Node.js server for rendering purposes

What is the best way to configure index files for both front-end (Angular 4 CLI) and backend (Angular 4 CLI) in order to manage two separate Angular apps? ...

I encountered an issue in my Angular application where I continually receive the error message stating "Module 'fs' cannot be found."

Within my service file, I have imported four crucial libraries: import * as async from "async"; import * as officegen from "officegen"; import * as path from "path"; import * as fs from "fs"; All seems to be functioning well with async, officegen, and pa ...

What is a superior option to converting to a promise?

Imagine I am creating a function like the one below: async function foo(axe: Axe): Promise<Sword> { // ... } This function is designed to be utilized in this manner: async function bar() { // acquire an axe somehow ... const sword = await foo ...

Unveiling the Power of USSD Codes with Ionic Typescript: A Comprehensive Guide

Currently diving into the world of Ionic 2 Framework, I find myself on a quest to discover how to execute USSD codes in Ionic using Typescript. Any guidance or assistance from the community would be greatly appreciated! ...

Improving the process of class initialization in Angular 4 using TypeScript

Is there a more efficient method to initialize an inner class within an outer class in Angular 4? Suppose we have an outer class named ProductsModel that includes ProductsListModel. We need to send the ProductId string array as part of a server-side reque ...

In Angular/Typescript, dynamically add a class to a `td` element when it is clicked. Toggle the class on and off

My problem arises when trying to individually control the arrow icons for each column in my COVID-19 data table. By using Angular methods, I aim to show ascending and descending arrows upon sorting but run into the challenge of changing arrows across all c ...

"Loop through an array using forEach leads to a subscription that

I am a beginner in Angular and struggling to understand how async functions work. I have written the following code, but I am encountering an error: GET https://localhost:44353/api/ecams/id/undefined 400 and ["The value 'undefined' is not va ...

Looking for the final entry in a table using AngularJS

Hey everyone, I'm dealing with a table row situation here <tbody> <tr *ngFor="let data of List | paginate : { itemsPerPage: 10, currentPage: p }; let i = index"> <td>{{ d ...

Allowing cross-origin resource sharing (CORS) in .NET Core Web API and Angular 6

Currently, I am facing an issue with my HTTP POST request from Angular 6. The request is successfully hitting the .net core Web API endpoint, but unfortunately, I am not receiving the expected response back in Angular 6. To make matters worse, when checkin ...

The rendering of the Angular 2 D3 tree is not functioning properly

Attempting to transition a tree created with d3 (v3) in vanilla JavaScript into an Angular2 component has been challenging for me. The issue lies in displaying it correctly within the component. Below is the code snippet from tree.component.ts: import { ...