Angular 2 (RC.6) 指令 @Input 正在转换为字符串
Angular 2 (RC.6) Directive @Input being converted to string
我在尝试将布尔值作为输入传递给我的指令时遇到一个奇怪的问题。出于某种原因 angular 正在将布尔值转换为字符串,尽管我已将其输入为布尔值。
组件,如您所见,背景是一个布尔值:
export class ModalsExportComponent extends Modal {
private background: boolean = false;
...
}
模板,这里我将背景绑定到我的指令输入:
<label for='showBackground' cmgSharedCustomCheckbox='{{background}}'><span></span>Include Background</label>
指令,我在这里定义输入并将其类型设置为布尔值,但是它以某种方式转换为字符串:
@Directive({
selector: '[cmgSharedCustomCheckbox]'
})
export class SharedCustomCheckboxDirective implements AfterViewChecked {
@Input('cmgSharedCustomCheckbox') isChecked: boolean;
constructor( private element: ElementRef,
private renderer: Renderer ) { }
public ngAfterViewChecked(): void {
this.renderer.setElementClass(this.element.nativeElement.children[0], 'checkbox-unselected', true);
}
@HostListener('click') click(): void {
console.log(typeof this.isChecked);
if (this.isChecked) {
console.log('here');
this.renderer.setElementClass(this.element.nativeElement.children[0], 'checkbox-unselected', false);
this.renderer.setElementClass(this.element.nativeElement.children[0], 'checkbox-selected', true);
}
}
}
您会注意到在我的点击主机侦听器中我有一个 this.isChecked 类型的控制台日志,它记录字符串。我如何让 angular 尊重我已经告诉它这个值是布尔值的事实?
如前所述here,
the material between the braces is a template expression that Angular first evaluates and then converts to a string.
要绑定非字符串值,请使用
<label for='showBackground' [cmgSharedCustomCheckbox]='background'>...</label>
我在尝试将布尔值作为输入传递给我的指令时遇到一个奇怪的问题。出于某种原因 angular 正在将布尔值转换为字符串,尽管我已将其输入为布尔值。
组件,如您所见,背景是一个布尔值:
export class ModalsExportComponent extends Modal {
private background: boolean = false;
...
}
模板,这里我将背景绑定到我的指令输入:
<label for='showBackground' cmgSharedCustomCheckbox='{{background}}'><span></span>Include Background</label>
指令,我在这里定义输入并将其类型设置为布尔值,但是它以某种方式转换为字符串:
@Directive({
selector: '[cmgSharedCustomCheckbox]'
})
export class SharedCustomCheckboxDirective implements AfterViewChecked {
@Input('cmgSharedCustomCheckbox') isChecked: boolean;
constructor( private element: ElementRef,
private renderer: Renderer ) { }
public ngAfterViewChecked(): void {
this.renderer.setElementClass(this.element.nativeElement.children[0], 'checkbox-unselected', true);
}
@HostListener('click') click(): void {
console.log(typeof this.isChecked);
if (this.isChecked) {
console.log('here');
this.renderer.setElementClass(this.element.nativeElement.children[0], 'checkbox-unselected', false);
this.renderer.setElementClass(this.element.nativeElement.children[0], 'checkbox-selected', true);
}
}
}
您会注意到在我的点击主机侦听器中我有一个 this.isChecked 类型的控制台日志,它记录字符串。我如何让 angular 尊重我已经告诉它这个值是布尔值的事实?
如前所述here,
the material between the braces is a template expression that Angular first evaluates and then converts to a string.
要绑定非字符串值,请使用
<label for='showBackground' [cmgSharedCustomCheckbox]='background'>...</label>