简体   繁体   中英

angular 2 custom directive OnInit

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)
    }

}

The syntax is wrong.

private defaultColor:string = 'green';

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

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)
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM