cobolstinks
cobolstinks

Reputation: 7153

angular 6 element boolean input parameter

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!

Upvotes: 8

Views: 12987

Answers (4)

Matthew Kooshad
Matthew Kooshad

Reputation: 319

since this was a top search result for me, sharing that starting with Angular v16.1, the @Input() decorator provides a transform function. We use the transform function to perform a transformation or execute other logic when an input property changes.

To further simplify our code, Angular introduced two built-in transformation functions: booleanAttribute and numberAttribute, either of which you can import and use as such:

import { booleanAttribute, Component, Input} from '@angular/core';

@Input({ transform: booleanAttribute }) showTitle = true;

Upvotes: 2

John H
John H

Reputation: 590

Boolean conversion can be done with a getter.

@Input('showTitle') showTitleStr: string;
get showTitle() {
    return this.showTitleStr === "true";
}

Upvotes: 0

Massimo Costa
Massimo Costa

Reputation: 1860

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>

Upvotes: 1

Martin Parenteau
Martin Parenteau

Reputation: 73761

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";
}

Upvotes: 10

Related Questions