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

I want to create a feature where a video will automatically play when a user clicks on a specific item in a list using Angular

Currently, I'm working on a project that involves displaying a list of videos and allowing users to play them in their browser upon clicking. The technology stack being used is Angular 2. Below is the HTML code snippet for achieving this functionalit ...

Guide to integrating a component within another component

Due to the size of this application, I am unable to utilize app.module. Unfortunately, the component I need to implement does not contain a module file. I have attempted to import it and utilize @NgModule, but it has not been successful. An error occur ...

Guide to creating unit tests for a button click function in an Angular project

I wrote some code for unit testing, but it doesn't seem to be working. I'm new to unit testing and would appreciate some guidance on how to use it. COMPONENT.HTML <button class="set-button" (click)="clickFunction()"> SA ...

The function this.listCatModel.push is not a valid operation

I have a dropdown that I want to populate using the following code: this.categoryService.GetListItem(this.GetAllcatListUrl).subscribe(data=>{ this.listCatModel=data, this.listCatModel.push({ id:0, name:'Main Category', parent ...

I want to showcase a Python array within an Angular framework

Here is an example array: [ { "TO":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c2b6a7b1b682a5afa3abaecca1adaf">[email protected]</a>", "FROM":"<a href="/cdn-cgi/l/email-protection" class="__ ...

To handle the input field efficiently in Angular, consider utilizing two <input type="radio"> elements

I am facing a challenge in my Angular 5 project where I have two radio buttons and need to dynamically update the value of formControlName and placeholder for an input field based on the selected radio button. How can I tackle this issue? <div clas ...

The continuity of service value across parent and child components is not guaranteed

My goal is to update a value in a service from one component and retrieve it in another. The structure of my components is as follows: parent => child => grandchild When I modify the service value in the first child component, the parent receives the cor ...

Developing a hidden entity that adopts an interface with multiple functions that have been overloaded

My TypeScript interface includes a single function named "send" with two different allowed signatures. export interface ConnectionContext { send(data: ConnectionData): void; send(data: ConnectionData, timeout: number): Promise<ConnectionData> ...

Could one potentially assign number literals to the keys of a tuple as a union?

Imagine having a tuple in TypeScript like this: type MyTuple = [string, number]; Now, the goal is to find the union of all numeric keys for this tuple, such as 0 | 1. This can be achieved using the following code snippet: type MyKeys = Exclude<keyof ...

Leveraging foreign key attributes within Angular templates

My technology stack includes Django for the backend with Django Rest Framework and Angular for the frontend. Within the backend, I have defined 2 models: class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_NULL, null= ...

What is the best way to encapsulate a slider within a fragment to prevent the occurrence of the "Type 'Element[]' is not assignable to type 'ReactNode'" error?

I'm encountering an issue with a Slider component in a NextJs landing page template. Every time I try to map through an array within the Slider component, I receive an error. I've attempted to find solutions online and came across this related th ...

Creating an RxJS observable stream from an event emitted by a child element in an Angular 2 component template

Currently incorporating Angular 2.0.0-rc.4 alongside RxJS 5.0.0-beta.6. In the midst of exploring various methods for generating observable streams from events, I find myself inundated with choices and would like to gather opinions. Recognizing that there ...

Unable to finish the execution of the ionic capacitor add android command

My current project needs to add android as a supported platform, so I tried running the command: ionic capacitor add android. However, when I run the command, it stops at a prompt asking me "which npm client would you like to use? (use arrow keys)", with ...

Tips on transferring key values when inputText changes in ReactJs using TypeScript

I have implemented a switch case for comparing object keys with strings in the following code snippet: import { TextField, Button } from "@material-ui/core"; import React, { Component, ReactNode } from "react"; import classes from "./Contact.module.scss" ...

Design buttons that are generated dynamically to match the style

I have a challenge in styling dynamically generated buttons. I've developed a component responsible for generating these dynamic buttons. const TIMER_PRESETS: Record<string, number> = { FIFTHTEENSEC: 15, THIRTYSEC: 30, FORTYFIVESEC: 45, ...

What are some ways to leverage a promise-returning callback function?

Here is a function that I have: export const paramsFactory = (params: paramsType) => { return ... } In a different component, the same function also contains await getPageInfo({ page: 1 }) after the return .... To make this work, I need to pass a cal ...

Using an additional router-outlet in an Angular 2 application: a step-by-step guide

I have been facing an issue with my angular2 app where I am attempting to use 2 router-outlets. Despite reading numerous blogs and conducting multiple Google searches, I have not been able to make it work. I would greatly appreciate any suggestions on why ...

Error message indicating that the preflight request failed access control check in Angular 5 with JWT OAuth integration

After spending hours reading through several posts, I have yet to find a solution to a very common problem. It seems that in order for my JavaScript code to access the resource, the server must include the Access-Control-Allow-Origin header in the response ...

connect the validation of forms to different components

I am currently working on components to facilitate the user addition process. Below is an example of my form component: createForm(): void { this.courseAddForm = this.formBuilder.group({ name: ['', [ Validators.required, ...

Roles in the Nebular system always have the granted status set to true by default

Hey there, I'm currently setting up Nebular to handle roles. Everything is working fine on the server side, but on the front end side, accessControl.isGranted() always returns true regardless of the role. Here's a snippet of the code I have been ...