Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Boolean @Input property getting set as string - binding nested properties

Tags:

angular

I have an outer component with a property:

Loading: Boolean = false;

this outer component is setting this property on a nested component:

<etp-loader text="loading..." loading="{{Loading}}"></etp-loader>

when I do typeof(this.Loading) on the nested component, I get string, which [what i believe] is what throws off the whole logic.

here's my nested component:

import { Component, AfterViewInit, OnInit, Input} from '@angular/core'
@Component({
    selector: 'etp-loader',
    template: `<div *ngIf="loading" class="progress" style="margin-left: 10%; margin-right: 10%;">
                <div class="progress-bar progress-bar-warning progress-bar-striped active" role="progressbar" aria-valuenow="100" aria-valuemin="0"
                        aria-valuemax="100" style="width:100%;">
                        {{text}}
                </div>
                </div>`
})
export class EtpLoaderComponent {
    @Input()
    text: string;

    @Input()
    loading: Boolean;    

    ngOnInit() {
        console.debug('init: loader state: ', 
                       this.loading, 
                       typeof(this.loading)); // => init: loader state:  false string
    }
}

edit - removed irrelevant bits

like image 843
Sonic Soul Avatar asked Jan 25 '17 16:01

Sonic Soul


1 Answers

If Loading is a boolean value, then use

[loading]="Loading"

{{}} is string interpolation and the result will always be a string.

Angular doesn't know about boolean attributes. If you just want to know if a property is set or not, you can use a setter like

isLoading:Boolean;

@Input()
loading set(value: Boolean) {
  this.isLoading = value != 'false';
}

and use it like

<etp-loader loading>

and isLoading will be set to true

like image 160
Günter Zöchbauer Avatar answered Oct 10 '22 03:10

Günter Zöchbauer