angular 2 个自定义指令 OnInit

angular 2 custom directive OnInit

我刚开始使用 Angular 2,我遇到了以下问题。

下面是一个简单的自定义指令,应该将字体着色为绿色。但是在 ngOnInit 中,它无法访问字符串 "defaultColor"、console.log returns "undefined".

知道为什么吗?

干杯!

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

}

语法错误。

private defaultColor:string = 'green';

使用 = 而非 : 分配值。 :是为字段定义类型。

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