简体   繁体   English

angular 2自定义指令OnInit

[英]angular 2 custom directive OnInit

i'm just getting starting on Angular 2 and i'm encountering the following problem. 我刚刚开始使用Angular 2,我遇到了以下问题。

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". 但是在ngOnInit中,它无法访问字符串“defaultColor”,console.log返回“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 : . 使用= not :指定值。 : is to define a type for the field. :是为字段定义类型。

Working Demo 工作演示

boot.ts 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 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)
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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