Search code examples
angularangular-directive

Angular 2 (RC.6) Directive @Input being converted to string


I'm having a weird issue with a boolean that I'm trying to pass to my directive as an Input. For some reason angular is converting the boolean to a string despite the fact I have it typed as a boolean.

Component, as you can see background is a boolean:

export class ModalsExportComponent extends Modal {
  private background: boolean = false;
  ...
}

Template, here I bind background to my directives input:

<label for='showBackground' cmgSharedCustomCheckbox='{{background}}'><span></span>Include Background</label>

Directive, here I define the input and set it's type as boolean, however it's converted to a string somehow:

@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);
    }
  }
}

You'll notice inside my click host listener I have a console log for the type of this.isChecked, which logs string. How do I get angular to respect the fact that I've told it that this value is a boolean?


Solution

  • As stated here,

    the material between the braces is a template expression that Angular first evaluates and then converts to a string.

    To bind non-string values, use

    <label for='showBackground' [cmgSharedCustomCheckbox]='background'>...</label>