8

I'm building out an angular element and passing some input params to it. I can pass some string input params just fine (ikrId and environment work perfectly) but struggling to pass a boolean value to the showTitle input property through an angular element (passing the showTitle property to the component from a parent angular component works just fine).

Here's component snippet:

export class MyComponent implements OnInit, OnDestroy {

  @Input() ikrId: string;
  @Input('environment') environment: IkrEnvironment = 'PROD';
  @Input('showTitle') showTitle = true;

Here is how I'm using it in plain old html:

<my-element environment="DEV" ikr-id="889fb69f-71a5-4881-8528-0b43a07599f0" show-title="false"></my-element>

But show title is not getting passed into my component, it's always true.

What am I missing here?

Thanks!

cobolstinks
  • 6,801
  • 16
  • 68
  • 97

3 Answers3

9

You could define the showTitle property as a getter/setter, and convert the string value to a boolean in the setter:

private _showTitle = true;

@Input('showTitle') 
get showTitle(): boolean {
  return this._showTitle;
}
set showTitle(value: boolean) {
  this._showTitle = "" + value !== "false";
}
ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
  • That is true for using this component from a parent angular component, but I'm specfically having in issue using this as an angular element. https://angular.io/guide/elements – cobolstinks Sep 26 '18 at 22:51
  • How are you passing your input elements? If you pre-load your input items, you should not have any issues using resolvers in your route. Then use activated route to pass your items to – harold_mean2 Sep 27 '18 at 00:40
  • 1
    Thanks for the help, I guess the only things I can send as Input params to the angular element are string variables, which makes sense because I need to provide them from html element attributes. – cobolstinks Sep 27 '18 at 13:06
1

the syntax to pass Input in the template is [<input_name>]="<value>"; you should use

<my-element [environment]="DEV" [ikrId]="889fb69f-71a5-4881-8528-0b43a07599f0" [showTitle]="false"></my-element>
Massimo Costa
  • 1,864
  • 15
  • 23
  • 1
    When you add the `[]` around the attribute names, the values will be evaluated as expressions. That means that any literal strings must be wrapped in quotes (inside the outer quotes), such as `[environment]="'DEV'"`. – seairth Jan 24 '19 at 16:25
  • Your answer applies to an Angular app but most likely the web compomnent will not be used inside another Angular app – Mick Jun 22 '21 at 11:27
0

Boolean conversion can be done with a getter.

@Input('showTitle') showTitleStr: string;
get showTitle() {
    return this.showTitleStr === "true";
}
John H
  • 502
  • 6
  • 9