Angular2指令不读取给定值

时间:2017-01-25 15:26:12

标签: angular angular2-directives

我需要一个将动态值绑定到元素的指令' s classList

指令

import { Directive, ElementRef, Input } from '@angular/core';

@Directive({
  selector: "[entityType]"
})
export class EntityTypeDirective {
  @Input() entityType: string;

  constructor(el: ElementRef) { 
    var labelClass = {
      C: "label-warning",
      F: "label-info",
      S: "label-success"
    };
    el.nativeElement.classList = `label ${labelClass[this.entityType]}`;
  }
}

标记

<span [entityType]="item.type">...<span>

问题

该指令绑定class="label undefined",因为entityTypeundefineditem.type是来自*ngFor转发器的值,我想将其传递给指令。

我哪里出错?

2 个答案:

答案 0 :(得分:3)

您应该使用ngOnInit lifecycle hook :)时出错了。这是@Input绑定以角度

完成的地方
@Directive({
  selector: "[entityType]"
})
export class EntityTypeDirective implements OnInit {
  @Input() entityType: string;

  constructor(private el: ElementRef) {}

  ngOnInit() {
    let labelClass: any = {
      C: "label-warning",
      F: "label-info",
      S: "label-success"
    };
    this.el.nativeElement.classList = `label ${labelClass[this.entityType]}`;
  }
}

答案 1 :(得分:2)

输入绑定在构造函数中不可用,而是使用ngOnInit

https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html