AlanObject
AlanObject

Reputation: 9943

Angular 2 component input without value

I want to create a component that has attributes that need no value. For example, instead of something like this: (which I have now)

<app-document [mode]="'edit'" ... ></app-document>

or

<app-document [editMode]="true" ... ></app-document>

I would rather have:

<app-document editMode ...></app-document>

So the component itself has to see whether the attribute editMode is present or not. This will look a lot cleaner when I have a lot of such attributes. I haven't seen any documentation on how to do this. Is it doable?

Upvotes: 22

Views: 9042

Answers (3)

james
james

Reputation: 4573

Updating the selected answer to use an input signal, you can now do the following:

import { input, booleanAttribute } from '@angular/core';
...
editMode = input(false, { transform: booleanAttribute } )

Upvotes: 0

0xcaff
0xcaff

Reputation: 13681

You can use boolean @Inputs to achieve this.

HTML:

<app-document [editMode] ...></app-document>

TS:

export class AppDocumentComponent {
  @Input() editMode: boolean = true;
  // ...
}

Now you have a boolean which you can use to change your behavior.

note for better understanding:

The default value true kicks in, if there is a (valueless) attribute. If there is none, editMode does not get the default value but a falsy undefined. (So, that is why this works).

Upvotes: 8

Alexandre Annic
Alexandre Annic

Reputation: 10738

Material2 wrote the following method:

/** Coerces a data-bound value (typically a string) to a boolean. */
export function coerceBooleanProperty(value: any): boolean {
  return value != null && `${value}` !== 'false';
}

Write something like that in your app-document component:

private _editMode: boolean;
@Input()
get editMode() { return this._editMode; }
set editMode(value: any) { this._editMode = coerceBooleanProperty(value); }

Then:

editMode == true
<app-document editMode></app-document>

editMode == false
<app-document></app-document>

If you use Material2 you can simply import the method as follows:

import {coerceBooleanProperty} from '@angular/cdk/coercion';

Upvotes: 38

Related Questions