Angular 8 throws a TS2339 error, yet the code is functioning perfectly and delivering the desired output

Upon compiling my code, I encountered the following error:

ERROR in src/app/home/home.component.ts:13:37 - error TS2339: Property 'name' does not exist on type 'string | Type'. Property 'name' does not exist on type 'string'.

13 this.pageName=route.component.name;

Surprisingly, the code works perfectly fine. The error only surfaces during the build process.

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

@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.sass']
})
export class HomeComponent implements OnInit {
pageName;
constructor(private route: ActivatedRoute,
private router: Router) { 
  this.pageName=route.component.name;
}
ngOnInit() {
}
}

I've even attempted changing the ES version, but unfortunately, it did not resolve the issue.

Answer №1

Aside from the information shared in this post, you have the option to utilize the Route's data property to provide your components with route-specific custom data.

data:

This is additional developer-defined data sent to a component through ActivatedRoute. By default, no extra data is transmitted.

Relying on developer-defined data is considered the safe and practical approach because once an application is created for production, class names are assigned arbitrary identifiers that should not be depended upon.

For example:

Routing config

const routes: Routes = [
  // ...
  {
    path: 'home',
    component: HomeComponent,
    data: {
      page: 'Home Page',
      class: 'super-sweet-home',
      color: 'blue',
      // ....
    },
  }
];

Accessing the data

  • Solution 1: Inside a component, such as HomeComponent.
private subscription: Subscription;

constructor(private route: ActivatedRoute) {}

ngOnInit() {
    this.subscription = this.route.data.subscribe((data: any) => { 
        /* Data will be available after successful navigation */ 
    });
}
public readonly currentPageData = new Subject<any>();

constructor(private router: Router) {
this.router.events.pipe(filter(event => event instanceof ActivationEnd))
  .subscribe(event => {
    this.currentPageData.next((event as ActivationEnd).snapshot.data as any);
  });
}

In a component, you can then inject the service and subscribe to the currentPageData of the SiteService, for instance:

constructor(private siteService: SiteService) {
    this.siteService.currentPageData.subscribe((data) => {
      /* Handle the received data */
    });
}

Lastly, remember to always unsubscribe from subscriptions.😬

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

Whenever you run the ng (Angular) command, it automatically opens up a text editor for you

Following a long break in my web development project using WSL2 (VS code), I decided to update all the tools with *npm i -g npm-check-updates, ncu -u, npm install* After updating, I found that I had version @angular/core@"~15.0.4. However, this versi ...

From JSON Schema to ng2-tree treemodel: Implementing in Angular 4

I am looking to create a dynamic Tree view of JSON in the UI that can be edited and saved on the fly. Currently, I am experimenting with TreeModel in Angular 4, but I'm facing challenges because the JSON schema and TreeModel schema are different. I ...

After compiling the code, a mysterious TypeScript error pops up out of nowhere, despite no errors being

Currently, I am delving into the world of TypeScript and below you can find the code that I have been working on: const addNumbers = (a: number, b: number) => { return a + b } Before compiling the file using the command -> tsc index.ts, the ...

Styles applied in the child component will have a cascading effect on the entire webpage

My webpage is divided into two parts: child1 and child2. Page Hierarchy: Parent Child1 Child2 Here are the CSS styles included in the page: Child1 -> z-index: 1 Child2 -> z-index: 2 What I want to achieve is to add a backdrop to the entire ...

Consistent tree view nesting persists with each refresh

I have recently transitioned to Angular (7) from a C# background. Currently, I am using asp.net core 2.2 along with the default template that comes with a new Angular project (home, counter, fetch-data). The tree view is bound and retrieved from a controll ...

Utilizing Emotion CSS to incorporate images into buttons

I'm trying to add some style to two buttons, Up and Down, by using emotion CSS but I'm having trouble. Currently, I typically style my elements within a function. Is there a way for me to accomplish this with emotion CSS? I checked out but still ...

React-querybuilder experiencing issues with validator functionality

While utilizing the react-querybuilder, I have encountered an issue with field validation not functioning correctly. Upon reviewing this StackBlitz, it appears that when clicking on Rule and checking all fields, there are no errors present. export const fi ...

Steps to reset Pipe in Angular 4

Is there a way to reinitialize a Pipe in Angular 4? I currently have a component that utilizes a Pipe. The component renders once with some data that uses the Pipe. If the data changes, the Pipe will also need to change. What is the best method to rein ...

Encountering a Problem with vue-check-view Library in Typescript

After successfully declaring the js plugin with *.d.ts, I encountered an issue where my view was blank after using .use(checkView). Does the library vue-check-view support Typescript? Error: Uncaught TypeError: Cannot read property '$isServer' o ...

The ngx-translate/core is throwing an error message that says: "HttpClient provider not found!"

I recently downloaded the ngx-translate/core package and have been diligently following the provided documentation. However, I'm facing an issue with getting the translations to work. Here are the steps I've taken: 1] Definition in the AppModul ...

Is there a way to reverse the color scheme on ngx-charts-heat-map?

I have been successfully using the ngx-charts-heat-map to generate a heat map. Everything seems to be working fine, but I am facing a small issue that I can't seem to figure out. Currently, the color of each cell on the map corresponds to its value ...

Select numerous files and conveniently delete them using the angular delete button

Background: In one of my tables, there is a column where users can either choose or upload files as input. I have implemented a feature that allows users to select multiple files at once. Issue at Hand: What I am trying to achieve is to have an 'x&ap ...

The custom validator in Material2 Datepicker successfully returns a date object instead of a string

Im currently working on developing a unique custom validator for the datepicker feature within a reactive form group. Within my code file, specifically the .ts file: form: FormGroup; constructor( private fb: FormBuilder, ...

Why am I encountering issues accessing a child property in TypeScript?

Here is some TypeScript code that I am working with: export interface SelectQuery_thing { __typename: "ThingQueryPayload"; content: (SelectQuery_thing_content | null)[]; pageInfo: SelectQuery_thing_pageInfo; } export interface SelectQuery_thing_con ...

Having trouble declaring a module in an npm package with Typescript?

I'm currently working on a project using Vue.js and TypeScript. Within project "A," I am utilizing a private npm package called "B," which serves as a component library. This package "B" also incorporates another library, 'tiptap,' which unf ...

The angular schematic workflow encountered an error while attempting to create a new project

Successfully installed Angular CLI, but I encountered an issue while creating a new project using 'ng new project name'. Some packages were created, but the installation failed with an unexpected end in JSON while parsing near.....'A85qs.... ...

Using `reduce` in TypeScript, you can organize an array of objects based on a shared property

Here is an example of an array: [ { id: '1', task: 'Grocery shopping', isImportant: true }, { id: '2', task: 'Meeting', isImportant: false }, { id: '3', task: &apos ...

You cannot call this expression. The type 'String' does not have any call signatures. Error ts(2349)

Here is the User class I am working with: class User { private _email: string; public get email(): string { return this._email; } public set email(value: string) { this._email = value; } ...

Steps for initiating a download for an Angular Progressive Web App

In the process of building an Angular PWA, I am interested in finding a method to display a popup notification for users who are browsing my app, prompting them to add it to their home screen. Is there a way to achieve this? ...

Steps for creating a dynamic validation using a new form control

I have an item that needs to generate a form const textBox = { fontColor: 'blue', fontSize: '18', placeholder: 'email', name: 'input email', label: 'john', validation: { required: false } ...