Angular 2: Component Interaction, optional input parameters
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
).
You can implement OnChanges or make the input a setter instead of a property to get your code executed when a value is actually passed.
export class child {
@Input set showName(value: boolean) {
this._showName = value;
doSomethingWhenShowNameIsPassed(value);
}
constructor() { }
}
You can use the ( ? ) operator as below
import {Component,Input} from '@angular/core';
@Component({
selector:'child',
template:`<h1>Hi Children!</h1>
<span *ngIf="showName">Alex!</span>`
})
export class ChildComponent {
@Input() showName?: boolean;
constructor() { }
}
The parent component that uses the child component will be as
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<child [showName]="true"></child>
<child ></child>
</div>
`,
})
export class App {
name:string;
constructor() {
this.name = 'Angular2'
}
}
LIVE DEMO