我需要一个将动态值绑定到元素的指令' 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"
,因为entityType
为undefined
。 item.type
是来自*ngFor
转发器的值,我想将其传递给指令。
我哪里出错?
答案 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