Angular 2 component input without value

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';

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).

Tags:

Angular