Is it feasible to retrieve the component's class name by using the selector name in Angular 2?

Is there a way in Angular 2 to retrieve the class name or reference of a component based on its selector name?

@Component({
  selector: 'selector-1',
  template: '<h1>Hello</h1>',
})
export class Component1 {}

@Component({
      selector: 'selector-2',
      template: '<h1>Hello</h1>',
    })
    export class Component2 {}

For example, can we access the class name of Component1 from within Component2 using the selector "selector-1"?

Example:

getComponentName(selectorName) {
 // return component name
}

getComponentName('selector-1');

Any assistance would be greatly appreciated.

Answer №1

There is a way to achieve this seamlessly as long as you refrain from invoking enableProdMode:

const element = document.querySelector('some-selector');
const debugElement = window.ng.probe(element);
const componentName = debugElement.componentInstance.constructor.name;

If not, you will be responsible for managing the component map on your own.

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

Tips on creating a personalized memoizeOne function that delivers the accurate data type

I've implemented a function for object memoization: import memoizeOne from 'memoize-one'; type ArrayWithOneObj = [Record<string, unknown>]; const compareObject = ([obj1]: ArrayWithOneObj, [obj2]: ArrayWithOneObj) => obj1 === obj ...

Steps for building a TypeScript project for server side using webpack

After configuring webpack to compile my project using TypeScript, I encountered an issue. The project is a server-side Node project that needs to be used as a linked library by another server-side project. When I compile it with webpack, I receive a window ...

ngModel displays the previously selected value in the md-select

Whenever I use console.log to display the value of selectedVendor in the method vendorUpdate, it is showing the previous value of selectedVendor rather than the new one. <div> <md-select id="vendorVariable" class="vm-select-wrap" ...

Replace current element in Angular 2

I am looking to change the current element during routing instead of simply adding to it. Below is the code I am currently using: <router-outlet> <div class="=row" style="height:30%"></div> <div class="=row"> <a ...

Typescript throwing an error stating "Error parsing: Enum member names must not begin with lowercase letters 'a' through 'z'"

Within my typescript project, I am utilizing the following enum type: export enum ModelAttributeTypes { binary = 'binary', binarySet = 'binarySet', bool = 'bool', list = 'list', map = 'map', num ...

A guide on implementing Redux Toolkit in an SPFX (typescript) project

I am currently working on developing SPFX components using typescript and webpack. My goal is to integrate redux toolkit into my project, but it is causing compilation errors. Here is what I have done so far: Created the project structure using yo Insta ...

Autocomplete feature shows usernames while storing corresponding user IDs

I am looking to enhance the autocomplete functionality in my application while also ensuring that the selected user ID is stored in the database. Specifically, I want the autocomplete feature to display user names for selection purposes, but instead of re ...

What is the best way to iterate over JSON data from an endpoint that contains multiple nested arrays using the .map() method?

Seeking to showcase weather API data from: () import Image from "next/image" interface Hour { time_epoch: number time: string temp_c: number temp_f: number is_day: number wind_mph: number wind_kph: number wind_deg ...

The component is unable to access the injected service from a separate module due to its null

In my Angular v6 project, there are 2 modules: app.module.ts, which includes the AppComponent and BoatComponent, and imports another module called draggable.module.ts. app.module.ts @NgModule({ declarations: [ AppComponent, BoatComponent ...

Filtering an array does not restrict the type of elements within it

I am facing a scenario where I have an interface containing two optional properties: interface A { one?: string; two?: string; } I want to pass these properties inside an array to a component that specifically requires string[] export const MyComponen ...

Issue with Angular: Unable to locate a differ that supports the object '[object Object]' of type 'object'. NgFor is only compatible with binding to Iterables such as Arrays

As someone who is new to Angular, I am facing a challenge while working on my portfolio project. The issue arises when trying to receive a list of nested objects structured like this: "$id": "1", "data": { &quo ...

The initial execution of the "ionViewDidEnter" method in Ionic 2 can be quite sluggish

Could you explain to me why there is a significant delay in loading the below functionality for the first time, but it loads normally on the second attempt? The same delay occurs on the actual device as well. Please refer to the attached video. Note : The ...

Workspace Settings cannot be saved due to an unregistered configuration

I've been attempting to change the StatusBar color in VScode Setting.json using Configuration and Workspace. However, I encountered an error when trying to make the update: Error: Unable to write to Workspace Settings because workbench.colorCustomizat ...

Creating a unique optional string array interface in TypeScript

I am looking to create an interface that includes optional string values. Here is what I have in mind: interface IEntity { values: ['RemainingUnits', 'ActualUnits', 'PlannedUnits'] } However, when implementing this inter ...

The Java Spring and Angular 7 application is missing a necessary file request component

I am facing an issue with the POST method in Angular 6. I am trying to send an image to the server. When I test it using Postman, my Spring Boot application works perfectly and saves the image on the server. However, when I attempt to send the image from m ...

"Encountering issue with auto-import suggestions failing to appear in VS Code version 1.88.0

After installing the necessary libraries for MUI, I encountered an issue where basic components like Typography were not showing up in intellisense. Instead, it was displaying @mui/icons-material. You can view screenshots below: https://i.stack.imgur.com/ ...

Encountering Invalid Chai attribute: 'calledWith'

I am currently in the process of implementing unit tests for my express application. However, I encountered an error when running the test: import * as timestamp from './timestamp' import chai, { expect } from 'chai' import sinonChai f ...

Is it necessary to create a unit test for a basic operation involving RxJS?

Imagine a straightforward class that triggers a new event to an RxJS subject whenever the window is resized. Disregard any perceived complexities, as the main point is that this class generates an event. export class ResizeService { priv ...

What is the process for declaring a member variable as an extended type in TypeScript?

Is it possible to declare a "member variable" as an "extension object" rather than a static type (without relying on an interface)? Imagine something like this pseudocode: class Foo { bar -> extends Rectangle; constructor(barInstance:IRec ...

Is it possible to capture and retain data, then transmit it x seconds after the initial data capture?

RxJS 4: I am attempting to capture and emit values after a certain interval of time has passed since the first value was received from a websocket. Essentially, once the first value is received, a timer will start to store subsequent incoming values and t ...