I have an implementation where parent wants to pass certain data to child component via the use of @Input
parameter available at the child component. However, this data transfer is a optional thing and the parent may or may not pass it as per the requirement. Is it possible to have optional input parameters in a component. I have described a scenario below:
<parent> <child [showName]="true"></child> //passing parameter <child></child> //not willing to passing any parameter </parent> //child component definition @Component { selector:'app-child', template:`<h1>Hi Children!</h1> <span *ngIf="showName">Alex!</span>` } export class child { @Input showName: boolean; constructor() { } }
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 ).
Use the @Input() decorator in a child component or directive to let Angular know that a property in that component can receive its value from its parent component. It helps to remember that the data flow is from the perspective of the child component.
Angular has an @Optional decorator, which when applied to a constructor argument instructs the Angular injector to inject null if the dependency is not found.
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
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