Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 component input without value

Tags:

angular

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?

like image 520
AlanObject Avatar asked May 15 '17 22:05

AlanObject


People also ask

How to pass@ input in Angular?

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!

How@ input works in Angular?

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

Are Angular inputs optional?

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


1 Answers

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';
like image 140
Alexandre Annic Avatar answered Sep 18 '22 13:09

Alexandre Annic