Passing a retrieved parameter from the URL into a nested component in Angular

I'm currently facing an issue where I am trying to extract a value from the URL and inject it into a child component. While I can successfully retrieve the parameter from the URL and update my DOM with a property, the behavior changes when I attempt to inject the same property into a child component.

Here is my parent component:

@Component({
  selector: 'app-posts',
  templateUrl: 
`
<div class="container">
  <h1><app-task-title [taskId]="router"></app-task-title></h1>
  <h2>{{router}}</h2>
  <app-tab [tacheLabelId]="router"></app-tab>
</div>
`,
  styleUrls: ['./posts.component.scss']
})
export class PostsComponent implements OnInit, DoCheck {

  /**Variables from the url */
  router! : number


  constructor(private route : ActivatedRoute) { }


  ngDoCheck(): void {
    this.router = Number(this.route.snapshot.paramMap.get('route'));
  }

  ngOnInit(): void {
  }
}

The h2 tag updates but the other components do not

This is my child component:

@Component({
  selector: 'app-task-title',
  template: `
      {{taskLabel}}
  `,
  styles: [
  ]
})
export class TaskTitleComponent implements OnInit {

  @Input() taskId! : number;
  taskLabel!: string;
  constructor() { }

  ngOnInit(): void {
    switch (this.taskId) {
      case 1:
        this.taskLabel = "Title 1"
        break;
      case 2:
        this.taskLabel = "Title 2"
        break;
      case 3:
        this.taskLabel = "Title 3"
        break;
      case 4:
        this.taskLabel = "Title 4"
        break;

      default:
        this.taskLabel = "Title 0"
        break;
    }
  }

}

Attempts made so far:

  1. Used the router property as a string and tried using the syntax:
    <h1><app-task-title taskId={{router}}></app-task-title></h1>
    , but encountered the same result.
  2. Implemented a method that returns the value in the DOM.

If you have insights on how the property behaves in the DOM, any explanation would be appreciated.

Answer №1

It seems like the issue could be related to the timing of when ngOnInit is being called in the child component, causing the taskId variable to not have a value yet. To ensure proper initialization, you can utilize the @Input decorator on a setter method instead :

export class TaskTitleComponent {

  // This attribute may no longer be necessary
  private _taskId! : number;
  taskLabel!: string;

  @Input()
  set taskId(taskId: number) {
    this._taskId = taskId;
    switch (this._taskId) {
      case 1:
        this.taskLabel = "Title 1";
        break;
      [...]
  }

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

Angular 7 ESRI loader search widget focus out bug: finding a solution

I am currently working on implementing an ESRI map using esri-loader in my Angular application. Everything seems to be working fine, but I am encountering an error when typing something into the search widget and then focusing out of it. "Uncaught Typ ...

"Encountering issues when trying to retrieve a global variable in TypeScript

Currently facing an issue with my code. I declared the markers variable inside a class to make it global and accessible throughout the class. However, I am able to access markers inside initMap but encountering difficulties accessing it within the function ...

What is the best way to dynamically change the main content based on the sidebar option chosen in a React application?

https://i.sstatic.net/fkIyh.png Currently, I am in the process of creating the layout for the page similar to the image provided. When a user selects option A from the sidebar, my goal is to display the corresponding content on the same page without navig ...

Mastering the proper implementation of the factory method in TypeScript

Trying to articulate this question is proving to be a challenge, but I'll give it my best shot. In Sharepoint, a default ListItem comes with properties like id, title, createdby, createddate, modifiedby, and modifieddate. Custom lists can have addit ...

Developing an NPM package within a yarn workspace monorepo featuring internal dependencies

Currently, I am working on a project where I am utilizing yarn workspace to develop a library that will eventually be published on NPM. This library has a dependency on a private core package within the same workspace. As per my understanding, the workspac ...

It appears that Stackblitz may have an outdated package.json file for older Angular projects, causing compatibility issues when running the project locally

Upon reviewing the package.json files for older Angular projects on Stackblitz, I have observed a pattern where Angular9 is listed under devDependencies while dependencies include older versions such as "@angular/core": "7.2.2" or "@angular/core": "6.1.10" ...

Fetching data from MongoDB, loading over 3000 entries and implementing pagination

I'm facing a challenge where I need to display more than 3000 results in an HTML table by fetching MachineID, Username, and Data from my MongoDB. However, I am encountering difficulties when trying to render this data using datatables. The MachineID ...

Having trouble getting Laravel and Angular to filter data by categories?

I am currently developing an ecommerce project using Laravel and Angular. I have products and brands associated with these products. In my function to retrieve the products in Laravel, I have used a nullable parameter like this: public function index($bran ...

Issue with VS code/Angular where linter is unable to detect components imported from shared modules

Having an issue with Angular materials components in my project. I have a shared module where I import all the necessary Angular materials modules, and the code runs fine. However, in my html files in VS Code, I see red squiggly lines under every Angular m ...

How do I specify the return type of a function in Typescript that can return more than one type?

I am facing a situation where I have a method called getFilters that retrieves various types of values. getFilters(): IListFilteringType {...} type IListFilteringTypeMultiSelect = (string | number)[]; type IListFilteringType = boolean | string | number | ...

Can a React function component be typed with TypeScript without the need for arrow functions?

Here is my current React component typed in a specific way: import React, { FunctionComponent } from "react"; const HelloWorld : FunctionComponent = () => { return ( <div> Hello </div> ); } export default HelloWorld; I ...

"Encountering difficulties while setting up an Angular project

I am currently working on setting up an Angular project from scratch. Here are the steps I have taken so far: First, I installed Node.js Then, I proceeded to install Angular CLI using the command: npm install -g @angular/cli@latest The versions of the ...

Ionic 4 Tabs with Smooth Scrolling

I recently started using Ionic 4 and I'm trying to create scrollable tabs in Ionic 4. However, when I include multiple tabs as shown in the code below, they become compressed and appear within the same viewing space. <ion-tab-bar slot="top"> ...

"Embedding a JSON object within a script tag in NextJS: A step-by-step

I've been working on configuring values within a Cookiebot initialization script tag in a NextJS project. The documentation suggests that I can set vendor properties by passing in a JSON object inside the script tag, like this (taken from this link): ...

I want to swiftly display the API response using console.log in Angular 8

My current setup involves using a service to log the response from a News API like this: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) exp ...

The Standalone Component does not appear for debugging in webpack:source when utilizing an incompatible version of Node

I have developed two components: https://i.sstatic.net/fSNqa.png However, after running ng serve, I am only able to see one component in the source of the Chrome browser: https://i.sstatic.net/VzdDS.png How can I troubleshoot this standalone component? ...

The error message "localStorage is undefined in Angular Universal" indicates that the local

I have chosen to utilize universal-starter as the foundation of my project. Upon initialization, my application reads a token containing user information from localStorage. @Injectable() export class UserService { foo() {} bar() {} loadCurrentUse ...

Sidenav Angular Material cdkScrollable is an effective tool for creating scrollable

In Angular Material CDK, there is a special Directive called CdkScrollable that allows you to monitor ScrollEvents within a specific container. I am currently attempting to retrieve the CdkScrollable associated with the default MatSidenavContent. Unfor ...

Angular 2: Enhancing Tables

I am looking to create a custom table using Angular 2. Here is the desired layout of the table: https://i.sstatic.net/6Mrtf.png I have a Component that provides me with data export class ResultsComponent implements OnInit { public items: any; ngO ...

Develop a new entity utilizing Array in Javascript

let DaysArray: any = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] I am looking to transform the above array into an Object structure as shown below: let DaysObject: any = { time: { headerName: "" }, m ...