Angular 2-component input without value
I want to create a component that has attributes that don't need value. For example, instead of something like this (now I have)
<app-document [mode]="'edit'" ... ></app-document>
or
<app-document [editMode]="true" ... ></app-document>
I would prefer:
<app-document editMode ...></app-document>
Thus, the component itself should see if the editMode attribute is present or not . It will look much cleaner when I have many attributes like this. I have not seen any docs on how to do this. Is it doable?
source to share
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 this in the component app-document
:
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 are using Material2 you can simply import the method like this:
import {coerceBooleanProperty} from '@angular/cdk/coercion';
source to share
You can use boolean @Input
to accomplish this.
HTML:
<app-document [editMode] ...></app-document>
TS:
export class AppDocumentComponent {
@Input() editMode: boolean = true;
// ...
}
You now have a boolean value that you can use to change your behavior.
Note: for better understanding:
The default true
takes effect if there is an attribute (no value). If it is not present, it editMode
does not get a default value, but false is undefined. (So ββthis is why it works.)
source to share