Angular2 指令不读取给定值
Angular2 Directive not reading given value
我需要一个将动态值绑定到元素的 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
转发器的值,我想将其传递给指令。
我哪里做错了?
你在应该使用 ngOnInit
lifecycle hook 的地方出错了 :)。这是在angular
中完成@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]}`;
}
}
输入绑定在构造函数中不可用,请改用 ngOnInit
。
https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html
我需要一个将动态值绑定到元素的 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
转发器的值,我想将其传递给指令。
我哪里做错了?
你在应该使用 ngOnInit
lifecycle hook 的地方出错了 :)。这是在angular
@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]}`;
}
}
输入绑定在构造函数中不可用,请改用 ngOnInit
。
https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html