Developing a custom directive in Angular 2 that implements the OnInit

Just delving into Angular 2 and encountering a minor hiccup.

Here's a quick custom directive designed to turn text green. However, there seems to be an issue with accessing the "defaultColor" string within ngOnInit - it keeps returning as "undefined" in the console log.

Any insights on what might be causing this?

Cheers!

import {Directive, ElementRef, OnInit} from 'angular2/core';

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

export class HighlightDirective implements OnInit{
    private elRef:ElementRef;
    private defaultColor: 'green';

    constructor(elRef:ElementRef){
        this.elRef = elRef;
    }

    ngOnInit():any {
        this.elRef.nativeElement.style.color = this.defaultColor;
        console.log(this.defaultColor)
    }

}

Answer №1

The syntax in this case is incorrect.

private defaultColor:string = 'green';

In this scenario, the assignment should use = instead of :. The usage of : is to specify a type for the field.

Answer №2

Check out the Live Demo

main.ts

import {Component,bind} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {FORM_DIRECTIVES} from 'angular2/form';
import {selectedColorDirective} from 'src/directive';
import {Directive, ElementRef, Renderer, Input,ViewChild,AfterViewInit} from 'angular2/core';
@Component({
  selector: 'my-app',
    template: `
          <div mySelectedColor> (div) I'm {{color}} color </div>
    `,
    directives: [selectedColorDirective]
})

export class AppComponent implements AfterViewInit{

 }

bootstrap(AppComponent, []);

directive.ts

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

@Directive({
    selector:"[mySelectedColor]", 
})

  export class selectedColorDirective { 

    private defaultColor: 'green';
     constructor(el: ElementRef, renderer: Renderer) {
      this.el=el;
        //this.el.nativeElement.style.backgroundColor = this.defaultColor; 
        this.el.nativeElement.style.color = this.defaultColor; 
     } 

        ngOnInit():any {
           this.elRef.nativeElement.style.color = this.defaultColor;
            console.log(this.defaultColor)
        }
    }

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

Using RXJS to filter data within nested properties using the pipe operator

I need to extract specific data from an API response using piping and filtering, but the response format is a bit challenging. Here is the JSON structure: { activeAwards: [ { name: 'x', status: 'valid' }, { name: 'y', statu ...

Saving the contents of a book in an Ionic mobile application

I'm working on an app that features an e-reader function for users to read a single book. Where should I save the text data for the book? I experimented with storing pages as .json files in the assets folder but ran into issues. The path to the asset ...

Angular2 Pipe - Currency code

Within the realm of angular2, pipes are utilized to format numbers. For instance: {{selectedTeam.teamSalary | currency: 'USD':true}} This results in an output like $152,524,668.00 The documentation on Angular2 Pipes lacks specific details, lea ...

Can errors be captured within a subscription or is it a futile endeavor?

Utilizing Angular 7, I am faced with an issue where I need to capture an error thrown due to receiving null values from an external api instead of the expected values. I am struggling to determine the correct approach in this situation. The service I hav ...

After successfully logging in with the angular2-token package, the Rails 4 API is responding with a 401 unauthorized error

In my current setup, I have a Rails 4 API with the gem Devise Token Auth hosted separately from my Angular 2 frontend application. To handle cross-origin requests, I have configured Rack CORS. Using Angular2-token on my front end, I can successfully sign u ...

Mastering Typescript lookup types - effectively limit the properties included in a merge operation with the Partial type

Exploring lookup types, I'm interested in creating a safe-merge utility function that can update an entity of type T with a subset of keys from another object. The objective is to leverage the TypeScript compiler to catch any misspelled properties or ...

An issue arose when attempting to forward the request with a self-signed certificate in the chain for the Angular CLI API

When working with IBM WebSphere Application Server (WAS), we are able to add certificates to the truststore in order to resolve any certificate-related issues. How should we handle this process when using npm? ...

Angular/HTML - Full JSON data can be shown completely, but attempting to display only a single attribute is

Currently, I am able to show a complete JSON array by using {{ Groups | json }}. When displayed on my html page, it looks like this: [ { "Id": 3, **"Name": "Name I"**, "Group_Name": "Group I" } ] However, when I try to do {{ Groups.Name }}, I encounter ...

Parsing JSON results in the return of two objects

I am analyzing a JSON file, expecting it to return Message[] using a promise. This code is similar to the one utilized in the Heroes sample project found in HTTP documentation { "data": [ {"id":"1","commid":"0","subject":"test1subject","body":" ...

Is it possible to assign default values to optional properties in JavaScript?

Here is an example to consider: interface Parameters { label: string; quantity?: number; } const defaultSettings = { label: 'Example', quantity: 10, }; function setup({ label, quantity }: Parameters = { ...defaultSettings }) { ...

Generating an instance of an enum using a string in Typescript

Having trouble accessing the enum members of a numeric enum in TypeScript using window[name]. The result is an undefined object. export enum MyEnum { MemberOne = 0, MemberTwo = 1 } export class ObjectUtils { public static GetEnumMembers(name ...

Is it possible for Angular 5 Service Worker to retrieve assets in the background?

As I delve into the world of progressive web apps with Angular 5, our CMS provides raw JSON data for our application. This JSON includes URLs to images hosted on our server. I can easily fetch a list of all images from our CMS, either in full or filtered b ...

Angular 2 throws a typescript error with code TS2339 stating that the property 'x' is not found on the type 'Y'

I'm having trouble converting an HTTP response into a DTO object. I can't seem to figure it out on my own and would appreciate some help with this issue. I have a service that uses an adapter class to convert the response into an array of objec ...

Is there intellisense support for Angular 2 templates in Visual Studio?

Is it possible for Visual Studio to provide autocomplete suggestions for properties of a Typescript component within a separate HTML view template? ...

A colleague's dependency is taking precedence over an NX Library

I'm working in a monorepo environment with nx, structured as follows: apps | - my-app libs | - common | - my-client After deployment, the libraries are published on npm with the names @my-org/my-client and @my-org/common. I have set up path ali ...

A helpful guide on retrieving user login details before launching an application by accessing JWT tokens stored in Cookies

In my angular project, I am implementing SSO login to generate a JWT token. Prior to initializing the application, I aim to retrieve the logged-in user's details and store them at runtime. Furthermore, I intend to utilize this user data in Route guard ...

Is there a way to toggle glyphicons in Angular 2 while also triggering their functions? Maybe using *ngIf?

I am working on a feature to add items to favorites in my Angular 2 app. The code snippet provided below is able to display either a filled star or an empty star based on the current status of the object. It also triggers the appropriate function to favori ...

When an asyncIterator is implemented in a unit test, it fails to resolve with any values

I am currently working with a readable stream from chatGPT and I am trying to assert it using an asyncIterator. However, despite my jest test running smoothly, there seems to be a logical error preventing it from resolving after each iteration. Can anyone ...

Is there a way I can ensure that function waits for another function to finish executing?

I am currently working with two functions: this.initData(resp.Id, "") this.initSelection(resp.results) My requirement is for the initSelection function to only fire after the initData function has completed, thus making initSelection function wa ...

Tips for resolving these dependency issues

After updating my Angular and my Angular project version to Angular 7, I encountered an issue when trying to run it: The package "@angular/compiler-cli" has an incompatible peer dependency with "typescript" (requires ">=3.1.1 <3.2", but would instal ...