angular 2 custom directive OnInit

12,816

Solution 1

The syntax is wrong.

private defaultColor:string = 'green';

The value is assigned using = not :. : is to define a type for the field.

Solution 2

Working Demo

boot.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)
        }
    }
Share:
12,816
Han Che
Author by

Han Che

Updated on June 26, 2022

Comments

  • Han Che
    Han Che almost 2 years

    i'm just getting starting on Angular 2 and i'm encountering the following problem.

    Below is a simple custom directive which is supposed to color the font green. However in the ngOnInit, it can't access the string "defaultColor", the console.log returns "undefined".

    Any clue why?

    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)
        }
    
    }
    
  • micronyks
    micronyks about 8 years
    Hi Gunter:\! I understand there is a sysntax error. Still my code works. I don't know how. I have implemented the same as user has suggested.
  • Günter Zöchbauer
    Günter Zöchbauer about 8 years
    I see. Might depend on the development tools you are using, how strict they are about syntax.
  • micronyks
    micronyks about 8 years
    I have implemented it with Plunker.Still don't know why. Nevermind !
  • Han Che
    Han Che about 8 years
    i was using webstorm and indeed private defaultColor: 'green'; was written in the tutorial...