Getting the component selector name within a Directive in Angular 4

Is it possible to access the selector name inside a Directive? I have multiple components using the same directive and need to identify the current component's selector. Here is an example:

<my-component1 *myDir="Var"></my-component1>
<my-component2 *myDir="Var"></my-component2>
<my-component3 *myDir="Var"></my-component3>

I want to get the current component selector name inside the Directive as shown below. Can anyone guide me on how to achieve this?

@Directive({
  selector: '[myDir]'
})
export class MyDirDirective {
   constructor() {
     this.currentSelector = getCurrentComponentSelector();
   }
}
@Input() set myDir(value:any){
  if(this.currentSelector === 'my-component1'){
      // Perform specific action based on the selector
  }
}

Answer №1

To retrieve the tag name, utilize the ElementRef in Angular.

constructor(private el: ElementRef) {
  const tagName = el.nativeElement.tagName;
}

ngOnInit() {
  const tagName = this.el.nativeElement.tagName;
}

(It is advisable to test both methods as there may be differences in their functionality)

Answer №2

This method offers a more streamlined approach that is compatible with AOT compilation and can be used even when you are not directly working within the specified component:

const components = [ MyComponent ];
/*
  ...
  Any relevant injection points
*/
constructor(private componentFactoryResolver: ComponentFactoryResolver) {
  // Iterate over each component
  components.forEach(element => {
    // Retrieve its resolved factory
    const factory = this.componentFactoryResolver.resolveComponentFactory(element);

    console.log('Factory:', factory);
    console.log('Selector:', factory.selector);
  });
}

Answer №3

After examining the templateRef, I found a component selector in a specific location which led me to use it as a temporary fix. Perhaps this workaround can assist others facing a similar issue.

this.templateRef['_def']['element']['template']['lastRenderRootNode']['element']['name'];


export class MyDirective {
   constructor(private templateRef: TemplateRef<any>) {
        this.currentSelector = this.templateRef['_def']['element']['template']['lastRenderRootNode']['element']['name'];
   }
}

@Input() set myDirective(value: any) {
  if (this.currentSelector === value){
      // Perform certain action based on condition
  }
}

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

Guide to updating the canvas in Chart.js based on a user-defined x-axis range

What I currently have: My chart.js canvas displays values on the x-axis ranging from 1 to 9. Users can input a new range to view a different scope, with default limits set at start = 3 and end = 6 in my repository. I already have a function that restrict ...

The functionality of the Array.sort method is known to cease functioning when the length of the Array exceeds

I have been working on a hybrid application that combines Angular and Ionic's framework. Recently, I discovered an issue with one of my functions not functioning as expected. Within my app, users are able to create a database of items stored as objec ...

The event listener for 'end' is not executing in a Node.js Firebase and Nylas Express application

I am currently working on setting up webhooks with Nylas. In their provided example, there is a middleware code that I am implementing in my TypeScript project using Firebase as the endpoint. When testing locally with ngrok, the middleware functions prop ...

When it comes to Typescript interfaces, subsequent fields are not overloaded or merged

So I've been exploring interfaces in TypeScript and their ability to merge different types, but I ran into a hiccup while transpiling my script. Here's where things went wrong in my interface: export interface StoreConfig extends Document, TimeS ...

Unselecting a line will result in the disabling of all chart lines

Currently, I am working with Primeng and incorporating multiple charts into my view. One feature of Primeng that I have successfully implemented is disabling lines. I am following this particular example: Primeng provides a handy function on their site: ...

Error Continues - "Exceeding Header Size Error"

In my current Next.js project, I have integrated a login system using NextAuth. Initially, everything was running smoothly. However, I started encountering an error whenever I attempted to retrieve the session. The Error: https://pastebin.com/Mh624N3c Du ...

Encountering failures while running Angular tests in GitHub Actions due to reading inner text (which works fine locally)

I am facing an issue in my GitHub actions workflow where Karma is unable to read the 'innerText' of a native element for an Angular project. The error 'TypeError: Cannot read properties of null (reading 'innerText')' is being ...

What is the procedure for implementing a RoleGuard in Angular 6?

Is there a way to retrieve the user role from the token? I've managed to fetch the token using the decoding feature of angular2-jwt, but when I try to apply it for accessing the admin route, it returns a value of false. Upon checking with console.lo ...

What is the best method for presenting backend exceptions in Angular?

I am currently working on setting up a WebAPI in .Net6 along with Angular. For the registration page, I have made the email unique (which serves as a username credential). Now, I want to notify users when they try to register with an email that is already ...

Getting Session from Next-Auth in API Route: A Step-by-Step Guide

When printing my session from Next Auth in a component like this, I can easily see all of its data. const session = useSession(); // ... <p>{JSON.stringify(session)}</p> I am facing an issue where I need to access the content of the session i ...

What is the best way to set up the --public-host for operating an Angular universal app in conjunction with an Ngin

Looking to implement HMR for a universal app, I want to confirm if it is possible. I have successfully set up and run an Angular 8 application using the default "ng new" command. To run it behind a reverse proxy, I modified npm start as follows: e.g. { " ...

Utilize ngx-filter-pipe to Streamline Filtering of Multiple Values

Need assistance with filtering an array using ngx-filter-pipe. I have managed to filter based on a single value condition, but I am unsure how to filter based on multiple values in an array. Any guidance would be appreciated. Angular <input type="text ...

Typescript error: Module not found or its corresponding type declarations cannot be located

After setting up a new project using create-react-app and yarn 2 in my vs code environment, I encountered an issue where the editor throws errors for every installed library. The error message I receive is: Cannot find module 'react' or its cor ...

Tips on optimizing NextJS for proper integration with fetch requests and headers functionality

I'm currently working on a NextJS project and following the official tutorials. The tutorials demonstrate how to retrieve data from an API using an API-Key for authorization. However, I've run into a TypeScript compilation error: TS2769: No ove ...

Navigating through Angular2 Components: Form validation fields access in Component.ts

Suppose I have a form that does not use FormGroup, and the view appears as follows: <form #f="ngForm" novalidate> <label>Email</label> <input type="email" [(ngModel)]="player.email" class="form-control" name="email" #email=" ...

Angular consistently marks form controls as mandatory, even in the absence of validators

Recently, I have been working on this code snippet where I make use of a deepCopy function to ensure that I avoid any unexpected pass by reference issues. const formGroup = this.allowances() formGroup.removeControl('allowanceEndDate') con ...

Angular Universal does not fully render on the server side

Currently, my project involves integrating Angular 4 with Angular Universal and Knockout. The main objective is to have the Angular application generate HTML on the server side for SEO purposes. As part of this process, I need to utilize KnockoutJs to bin ...

"Implementing an abstract method in a class by overloading it with a generic type that

// Greetings from the TypeScript Playground, a platform where you can experiment with TypeScript code. type Constructor<T> = new (...args: any[]) => T; class ServiceChecklistResponse { } class AnotherModel { } abstract class AbstractView { ...

Discovering the number of items that have been filtered in isotope-layout using React and Typescript

Currently, I am utilizing the isotope-layout library within a React (Typescript) project. Although I have successfully implemented filtering on my page, I am unsure of how to retrieve the count of the filtered items. Upon loading the page, Isotope is init ...

WebStorm is not implementing the exclude option as specified in the tsconfig.json file

Is there a way to exclude a directory from TypeScript compilation in WebStorm? Despite specifying the exclusion in the tsconfig.json file, it seems that WebStorm doesn't respect the setting and compiles everything in the root directory. However, runn ...