What is the best way to obtain a reference to an instance of my Angular 2 directive?

Angular 2 rc 5 was written using typescript 1.9

I am trying to access the instance of my attribute directive. Although I am using ViewChild, which typically works with components, it is giving me a handle to the element containing the directive.

template

<span myHighlight #directive> Highlight me! </span>

component

/** Trying to get a handle to the directive but receiving the span element instead */
@ViewChild('directive') directive:HighlightDirective;

ngAfterViewInit(){
   console.log(this.directive);
}

directive

@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
    constructor(el: ElementRef, renderer: Renderer) {
       renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'yellow');
    }
}

Check out the live example here

The <span> element is being displayed in the console, indicating that ViewChild is not returning what I expected. How can I obtain a reference to the actual directive instance?

Answer №1

@ViewChildren('directive', {read: HighlightDirective}) directive:HighlightDirective;

alternatively

@ViewChildren(HighlightDirective) directive:HighlightDirective;

however, this second method will retrieve the first instance of HighlightDirective, not a specific one.

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 effectively implement form-control with mat-radio-group?

UPDATE: Check out my code on stackblitz I'm facing an issue with my form layout. The form control rows are overlapping with the radio button rows. I need help to resolve this problem. Here is a snippet of my code: <form [formGroup]="formGroup" (n ...

Having trouble with firebase admin code completions not functioning properly in vscode?

I've attempted to install the Typescript integration for Firebase using: npm install --save-dev @types/firebase Unfortunately, I have not had any success. The "firebase-admin" and "firebase-functions" packages do not provide code completion or intel ...

Experiencing CORS problem in Ionic 3 when accessing API on device

I am a newcomer to IONIC and I am utilizing a slim REST API with Ionic 3. Currently, I am encountering the following error: "Failed to load : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin&apos ...

How to access parent slider variables in an Angular component

I've developed a slider as the parent component with multiple child components. See the demo here: https://stackblitz.com/edit/angular-ivy-gcgxgh?file=src/app/slide2/slide2.component.html Slider in the parent component: <ng-container *ngFor=&quo ...

Conceal Columns in DevExtreme with Angular2 EditMode

Is there a way to conceal a DataGrid Column while in EditMode by utilizing DevExtreme and Angular2? <h3>Test</h3> <dx-data-grid id="gridContainer" [dataSource]="xxx" [allowColumnReordering]="true" [allowColumnResizing]="true" [rowAltern ...

The synergy between ternary operators and Vue filters

Recently, I came across a peculiar issue while working with Vue. Take a look at the code snippet from vue.html: <label :text= "$props.information ? (($props.information.primary || $props.information.secondary) | myFilter) : `No info`"> </lab ...

Tips for utilizing the "??=" syntax in Typescript

let x; x ??= 'abc' console.log(x); // abc Running the code above in the browser console does not cause any issues. However, when attempting to run it in TypeScript, an error is thrown. SyntaxError: Unexpected token '??=' Here is my c ...

What is the best way to incorporate an automatic scroll to the following section on a single page website

My goal is to implement a feature that enables automatic scrolling between sections as the user scrolls up or down. The smooth transition should occur when the user reaches halfway through each section, seamlessly moving to the next screen on the same page ...

The element is implicitly imparted with an 'any' type due to the incapability of utilizing an expression of type 'number' to index the type '{}'. This error occurs in the context of VUEJS

I have encountered an issue that I have been struggling to resolve despite trying numerous solutions. The problem arises while working on a project using Vue. Here is how I have structured my data: data(){ return{ nodes: {}, edges:{}, ...

Utilizing headers in apollo watchQuery results in undefined data

Utilizing the apollo-angular package for querying our backend using graphQL has been smooth sailing. However, things take a turn when I attempt to include headers in the query. I am specifically adding a custom header to extract flattened data from the ba ...

What is the best way to create a sortable column that is based on a nested object within data.record?

I am utilizing jquery jtable to showcase some data in a table. I have been using the following code snippet for each field in the table to display the data and enable sorting: sorting: true, display: (data) => { return data.record.<whatever_value ...

What is the proper way to display the date and time 2021-11-14T18:30:00.000+00:00?

Here is my ts file code: mydate: Date = new Date('2021-11-14T18:30:00.000+00:00'); However, I want the date to be in this format:- 07-July-2022 If anyone can assist with achieving this format, it would be greatly appreciated. Thank you! ...

Using @Input to pass data from a parent component to a

Looking to modularize the form code into a separate component for reusability? Consider using @Input and referencing it in the HTML to pass values to the post method. Here's how you can achieve this: Previously, everything worked smoothly when all th ...

Ways to remove redundant code from multiple service calls

Within my DataService, I have set up an observable for various API calls. I am looking to streamline the process by creating a reusable block of code to be used in each HTTP request. export class DataService { constructor( private http: HttpClient, ...

What is the best way to transform a string into an array?

After receiving an object from the http response, it looks something like this: {"[3, company1]":["role_user"], "[4, company2]":["role_admin"] } The key in the object is represented as an array. Is there a method in ...

I'm struggling to grasp the utilization of generics within the http.d.ts module in Node.js code

type RequestHandler< Request extends **typeof IncomingMessage = typeof IncomingMessage**, Response extends **typeof ServerResponse = typeof ServerResponse**, > = (req: InstanceType<Request>, res: InstanceType<Response> ...

Issue: UNSUPPORTED: The keyword "id" is not supported, please use "$id" for the schema ID after upgrading to Angular13

After upgrading from Angular 12 to Angular 13, I encountered an error while running my e2e tests. How can I go about identifying the root cause of this issue? I am able to compile with 'ng build'. /opt/wdio/node_modules/@angular-devkit/core/nod ...

transform array elements into an object

I encountered the following code snippet: const calcRowCssClasses = (<string[]>context.dataItem.cssClasses).map( (cssClass) => { return { [cssClass]: true }; } ); This code block generates an array of objects like ...

Guidelines for Nestjs class-validator exception - implementing metadata information for @IsNotIn validator error handling

I have a NestJs data transfer object (dto) structured like this import { IsEmail, IsNotEmpty, IsNotIn } from 'class-validator'; import { AppService } from './app.service'; const restrictedNames = ['Name Inc', 'Acme Inc&ap ...

Angular 4 - Resolve ngModelChange Error: Property '...'is Undefined When Binding Two Select Form

I need assistance with implementing a functionality in Angular 4. I have a JSON model that contains information about books, including their titles and authors. I want to create two select form elements (dropdowns): the first dropdown should display the ti ...