Boolean inputs to angular 2 component

angular

Solution

This fails, because the usage `<generic-selector showControls="false"></generic-selector>` sets showControls as the string "false", which is truthy, rather than as the boolean value. So I have to get round it by adding a lot of mess to the component to take in the input and convert to a boolean based on whether it is being given the string "false" or not. A non-messy way to sort this would be appreciated, but I'd prefer being able to do the other option above.

using binding

<generic-selector [showControls]="false"></generic-selector>

Problem

I'm trying to write a component to be reused across my application, which will sometimes show a control button and sometimes not. Ideally, I'd want to get this from the presence or absence of an attribute, so that using the component would look something like `<generic-component hideControls></generic-component>`, with a boolean variable in my component based on whether that attribute is present, but I can't see a way to do this. Is there a way to do this? I have tried with the slightly more messy version below (although ideally I would not need to set a value on showControls/hideControls); generic.component.html ``` <div> <div>Stuff</div> <div *ngIf="showControls">Controls</div> </div> ``` generic.component.ts ``` // imports etc. @Component({ selector: 'generic-selector', templateUrl: 'generic.component.html' }) export class GenericComponent implements OnInit { @Input() public showControls: boolean = true; // other inputs and logic } ``` This fails, because the usage `<generic-selector showControls="false"></generic-selector>` sets showControls as the string "false", which is truthy, rather than as the boolean value. So I have to get round it by adding a lot of mess to the component to take in the input and convert to a boolean based on whether it is being given the string "false" or not. A non-messy way to sort this would be appreciated, but I'd prefer being able to do the other option above.

Original source

Related problems