Retrieve all elements within an Angular6 Directive that share the same name as the Directive

I have created a custom Directive called isSelected and applied it to several elements in different components as shown below:

<i isSelected class="icon"></i>
<i isSelected class="icon"></i>
<i isSelected class="icon"></i>
<i isSelected class="icon"></i>

Now, I am trying to figure out how to access the elements that have the 'isSelected' Directive within the Directive itself.

@Directive({
 selector: '[isSelected]'
})
export class IsSelectedDirective {
   //I need to retrieve all elements with my directive
}

Check out the StackBlitz code

In the provided StackBlitz code, when hovering over an h1 tag, the hovered tag should have opacity of 1 while the rest of the h1 tags should have opacity of 0.5.

Feel free to leave a comment if you require any further information.

Answer №1

One way to implement this functionality is by utilizing the constructor of your directive. Here is an example:

constructor(private el: ElementRef, private myService: MyService) {
    myService.push(el); 
}

Each time a constructor of an element applying this directive is called, the element is pushed into an array maintained by a service.

For instance, you can create a service like this:

@Inject()

export class MyService{
 private elementArray: Array<ElementRef> = [];

 public push(el: ElementRef) {
    this.elementArray.push(el):
 }
 public getElements() {
 return this.elementArray;
 }
}

By using this service within the directive, you can access the list of all elements that have applied the directive.

Answer №2

After careful consideration, I stumbled upon this method.

@Directive({
 selector: '[isSelected]'
})
export class IsSelectedDirective {
  allItems;

  ngOnInit() {
    this.renderer.addClass(this.elem.nativeElement, 'isSelected')
  }

  ngAfterViewInit() {
    this.allItems = this.document.querySelectorAll('.isSelected');
  }
}

This technique involves adding a class during directive initialization and then querying the elements with the added class when the view is initialized. It proved successful for me.

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

How to Programmatically Assign Bootstrap Class to an Element Using Angular 2

I am working on a page with several input boxes that need to be flagged for certain criteria. <div class="form-group"> <label class="d-block">Allowance Type</label> <div class="input-group"> ...

Resolve the Angular proxy issue with the backend

Attempting to troubleshoot a similar problem, but struggling to understand why it's not functioning correctly. The API I am working with is located at: localhost:8080/api/acl/authorize Here is the HTTP client code: const AUTH_URI = "/api/acl/&q ...

I am encountering an issue with Wedriver.IO where screenshots of executions on a Remote Selenium Grid Hub are not being included in my Allure Reports

wdio.conf.ci.js: The following code snippet has been added. afterTest: function(test, context, { error, result, duration, passed, retries }) { if (passed){ browser.takeScreenshot(); } }, I expect to see a screenshot attachment in the bottom right corn ...

Icon Searchbar Feature in Ionic 2

I am currently working with Ionic2 and have integrated the ion-searchbar component into my project: https://i.sstatic.net/CqmF4.png Question Would it be possible to customize the search icon? The default icon is a magnifying glass, but I would like to r ...

Obtain information from a JSON file based on a specific field in Angular

The structure of the JSON file is as follows: localjson.json { "Product" :{ "data" : [ { "itemID" : "1" , "name" : "Apple" , "qty" : "3" }, { "itemID" : "2" , "name" : "Banana" , "qty" : "10" } ] ...

Exploring generic types using recursive inference

The scenario: export type SchemaOne<T> = | Entity<T> | SchemaObjectOne<T>; export interface SchemaObjectOne<T> { [key: string]: SchemaOne<T>; } export type SchemaOf<T> = T extends SchemaOne<infer R> ? R : nev ...

Updating Angular from version 9 to 11 causes issues with router.navigate not being able to properly load a new component

After updating my Angular project from version 9 to 11 (with an upgrade to version 10 in between), I encountered a strange routing issue. In version 9, the method below worked perfectly fine. However, in version 11, although the URL changed to 'upload ...

Setting up Electron with React and TypeScript: A Comprehensive Guide

I've been developing an app using Electron, React (jsx), and Babel. However, I recently made the switch to TypeScript and I'm struggling to get everything functioning properly. The npm packages I've tried only work for either React or TypeSc ...

Error: The variable "prisma" is not defined in this context - Next.js version 14

While working with Prisma and next.js 14, I encountered an issue with the Stripe payment API. The error message ReferenceError: prisma is not defined popped up. How can I resolve this? import { NextApiRequest, NextApiResponse } from "next" import ...

Angular 2 - Implementing click event functionality to add an item

I've searched for a solution to this before, but the best answer I could find was from 9 months ago: here and it doesn't work with the latest Angular version. Is there a way to add a new item (<li> or any other) to my HTML with a simple cl ...

The webpack-dev-server is missing the required module

Having trouble with starting my Angular project even after creating a new one using ng new AppName. When I run the project with ng serve, I still encounter an error that persists. Can someone help me resolve this issue? Error: Module not found - Error: Ca ...

What could be causing the React text input to constantly lose focus with every keystroke?

In my React project using Material-UI library, I have a component called GuestSignup with various input fields. const GuestSignup = (props: GuestSignupProps) => { // Component code goes here } The component receives input props defined by an ...

What steps can I take to ensure that the upper and left sections of a modal dialog remain accessible even when the size is reduced to the point of overflow?

One issue I'm facing is with a fixed-size modal dialog where part of the content gets cut off and becomes inaccessible when the window shrinks to cause an overflow. More specifically, when the window is narrowed horizontally, the left side is cut off ...

When utilizing the catch function callback in Angular 2 with RxJs, the binding to 'this' can trigger the HTTP request to loop repeatedly

I have developed a method to handle errors resulting from http requests. Here is an example of how it functions: public handleError(err: any, caught: Observable<any>): Observable<any> { //irrelevant code omitted this.logger.debug(err);//e ...

The program abruptly shut down with error code 127. Any idea why this occurred?

I'm having issues while attempting to create an app from a script. When I run "ionic serve," the following errors occur: [error] Error: Job name "..getProjectMetadata" does not exist. at Observable._subscribe (C:\Users\Bhanu\Desktop&bs ...

Guide on incorporating finos/perspective into an Angular 8 project using https://perspective.finos.org/

I am looking for guidance on incorporating Finos/Perspective Datagrid into my Angular 8 application. I need to input data in JSON format and have it output as a Datagrid. Any sample code or examples would be greatly appreciated. You can find the GitHub re ...

What is the best way to mock a Typescript interface or type definition?

In my current project, I am working with Typescript on an AngularJS 1.X application. I make use of various Javascript libraries for different functionalities. While unit testing my code, I am interested in stubbing some dependencies using the Typings (inte ...

Currying disrupts the inference of argument types as the argument list is divided in half, leading to confusion

One of my favorite functions transforms an object into a select option with ease. It's written like this: type OptionValue = string; type OptionLabel = string; export type Option<V extends OptionValue = OptionValue, L extends OptionLabel = OptionL ...

Issue with Angular 4: NgModel not functioning properly for setting value to "date" input field

I am facing an issue while trying to set a value to an Input of type "date" in Angular 4. The structure of my field looks like this: <input type="date" class="form-control" ([ngModel])="edt_object.list_changedate" ...

I'm sorry, we couldn't locate the module: Unable to find the path '../types/index'

After spending an hour attempting to troubleshoot this issue, I am still unable to find a solution. I have stored index.d.ts in the types folder. The content of the types file is as follows: export interface tag { created_at: string id: nu ...