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?
The first step to passing data into an Angular component is to create a custom property to bind to. This is done via “input” binding to pass data from one component to another (typically parent to child). This custom input binding is created via the @Input() decorator!
@Input is a decorator to mark a property as an input. @Input is used to define an input property, to achieve component property binding. @Inoput decorator is used to pass data (property binding) from parent to child component. The component property should be annotated with @Input decorator to act as input property.
Input values are optional by default. Your code will fail only when it tries to access properties of inputs that are not actually passed (since those inputs are undefined ).
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With