Are Angular2 Injectables for creating instances or referencing the same instance?

Exploring the world of ES6, TypeScript, and Angular2 has been quite a journey for me. I recently delved into directives and here's what I found...

import { Directive, ElementRef, Input, Renderer } from '@angular/core';

@Directive({ selector: '[myHighlight]' })

export class HighlightDirective {
    constructor(el: ElementRef, renderer: Renderer) {
       renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'green');
    }
}

However, my attempts with different variations didn't quite yield the expected results...

import { Directive, ElementRef, Input, Renderer } from '@angular/core';

@Directive({ selector: '[myHighlight]' })

export class HighlightDirective {
    constructor() {

    console.log(new ElementRef())
       //renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'green');
    }
}

I even tried this alternative approach...

import { Directive, ElementRef, Input, Renderer } from '@angular/core';

@Directive({ selector: '[myHighlight]' })

export class HighlightDirective {
    constructor(ElementRef, Renderer) {

    console.log(new ElementRef())
       //renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'green');
    }
}

The confusion between using el: ElementRef syntax and creating a new instance with new ElementRef still lingers in my mind. Can someone explain the difference and the underlying logic behind them? How does el: ElementRef relate to or compare with regular object instantiation in JavaScript or ES6? Appreciate any insights in advance :)

Answer №1

The foundation of Angular 2's Dependency Injection (DI) mechanism lies in understanding the importance of constructor injection. By requesting services or references within your component through the constructor, you are essentially telling Angular, "I need these objects - ElementRef and Renderer - for my directive to function properly."

These objects are provided by the DI framework during the directive's lifecycle. It is crucial to grasp this concept, as outlined in an insightful article that I highly recommend reading:

In scenarios where the constructor is left empty, meaning no dependencies are injected into the directive upon creation, attempting to manually create an ElementRef instance using new() will not suffice. Additional dependencies such as nativeElement are required, as detailed in the documentation here: https://angular.io/docs/js/latest/api/core/index/ElementRef-class.html Without providing all necessary dependencies, the directive cannot be instantiated.

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 can we strengthen the type checking when defining the sorting function for json properties?

When dealing with a json structure from a service that contains .attributes json values, I often find myself needing to sort either by id from the DTO or by several attributes from the IContactsAttributes. The microservice returns this specific structure: ...

Setting up StrongLoop LoopBack MongoDB datasource for successful deployment on Heroku

Currently, I am utilizing LoopBack version 1.6 and have a local mongoDB server operational for development purposes with the following datasource configuration: "mongodb": { "defaultForType": "mongodb", "connector": "loopback-connector-mongodb", ...

Retrieving information from a child modal window in an Angular parent component

In the scenario where there is data in two tables on the left and right sides, a modal popup window will open when a user clicks a link from the parent component. Upon selecting a radio button from the window, it should correspond to the selected link in t ...

The type definition file for 'bson' could not be located. It appears to be missing from the program due to being the entry point for the implicit type library 'bson'

I recently set up a new Typescript/React project and encountered the following error in the tsconfig.json file: "Cannot find type definition file for 'bson'. The file is in the program because: Entry point for implicit type library 'bson&ap ...

Navigating the contents of the text file using TypeScript

After locating the file flight.txt, I have obtained the following flight information: 1 DFW BOM 2016-05-20 12:20 2016-05-21 02:40 1084.00 JetAirways 100 2 DFW DEL 2016-04-24 17:15 2016-04-25 07:20 1234.00 Lufthansa 100 3 DFW FRA 2016-06-05 13:30 2016-06-0 ...

How to configure headers in Angular 5

When logging in a user, the function returns a token in the response body which is then set in the headers. this.headers = new HttpHeaders({'Content-Type': 'application/json'}); loginUser(email, password) { const body = {emai ...

The Mongoose query for the id field retrieves both the id and _id values

Within my Mongoose schema, there is a specific field named id which holds a unique identifier for each document. This operates using the same system as the standard _id field as shown below: var JobSchema = new mongoose.Schema({ id: { type:String, requi ...

What is the best way to retrieve the previous value of a reactive form?

I currently have a form set up with the following structure: this.filterForm = this.fb.group({ type: [null, [Validators.required]]}); As I monitor any changes that occur, I use the code snippet below: this.filterForm.controls["type"].valueChanges. ...

Exploring how Django utilizes sessions in conjunction with Angular's cookies while integrating with Django Rest

Looking for a comprehensive example demonstrating how Django Rest Framework can send a session key to Angular for storage as a cookie. I've been trying to figure this out for days... I have Django running on port 8000 and in Angular's ng serve, ...

How can I transfer information from an HTML file (using the ejs template engine) to Node.js?

Currently, I am working on my own project using a combination of Node.Js (Express), MongoDB, JavaScript/jQuery, and HTML with EJS as the template engine. So far, I have some understanding of how to send data from the Node.js router to views and how to sen ...

Techniques for importing esm libraries without requiring the "type": "module" declaration in the package.json configuration file

I have successfully implemented a TypeScript Node project but now I am facing an issue while trying to integrate the VineJS library into the project. The problem arises because VineJS is exclusively an ESM (ECMAScript Module) package, and when adding it to ...

Using AngularJS to inject a variable into the standard filter

Currently, I am attempting to develop a custom filter that mimics the functionality of the standard Angular filter in HTML, with the distinction that it accepts a variable as input rather than a fixed value. For instance, within my html document, you may ...

Managing the position of the caret within a content-editable div

I need help with editing a contenteditable div in HTML <div contenteditable="true" id="TextOnlyPage"></div> Here is my jQuery code: var rxp = new RegExp("(([0-9]+\.?[0-9]+)|([0-9]+))", "gm"); $('#TextOnlyPage').keyup(function( ...

How come ts-jest in jest is affecting my JavaScript files?

As a newcomer to using jest with ts-jest, I am facing an error that I can't quite comprehend: $ jest FAIL src/lib/Core/Storage/JsonStorage.test.ts ● Test suite failed to run Jest encountered an unexpected token Jest failed to parse a f ...

JavaScript Slideshow Transition Techniques

I'm struggling to create a slideshow gallery using Javascript. However, I'm facing an issue where the code instantly jumps from ferrari.jpg to veyron.jpg, completely skipping over lamborghini.jpg. <!DOCTYPE html> <html> <head> ...

Jest's it.each method is throwing an error: "This expression is not callable. Type 'String' has no call signatures."

I've been attempting to utilize the describe.eachtable feature with TypeScript, but I keep running into an error message stating: "error TS2349: This expression is not callable. Type 'String' has no call signatures." Below is my code snippe ...

JavaScript: retrieving undefined value from a text element

My goal is to retrieve the text entered into each textbox by querying and looping through their ID tags. However, when I attempt to print what I have retrieved, it always displays "undefined". Seems like your post consists mostly of code: </h ...

javascript guide on eliminating a particular element from an array by detecting the clicked item

I am looking to enhance my list by enabling the functionality to remove items permanently from the array when they are clicked. Although I have successfully implemented the removal feature using remove(), the issue arises when a new item is added to the ar ...

What steps can be taken to utilize ajax for pagination and retrieving data efficiently?

My goal is to retrieve 3 specific data points from a webpage using the ajax get method. Here is the javascript code: <script type="text/javascript"> var busy = false; var limit = 15; var offset = 0; var id = 150; function displayRecords( ...

Is MongoDB still displaying results when the filter is set to false?

I am currently trying to retrieve data using specific filters. The condition is that if the timestamp falls between 08:00:00 and 16:00:00 for a particular date, it should return results. The filter for $gte than 16:00:00 is working correctly, but the $lte ...