Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

question from:https://stackoverflow.com/questions/43874604/boolean-inputs-to-angular-2-component

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
434 views
Welcome To Ask or Share your Answers For Others

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...