Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Component Interaction, optional input parameters

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() { }  } 
like image 445
Sumit Agarwal Avatar asked Sep 27 '16 06:09

Sumit Agarwal


People also ask

Can input be optional in Angular?

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

What does @input do in Angular?

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.

What is the use of optional () in Angular?

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.


1 Answers

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

like image 108
Aravind Avatar answered Sep 19 '22 17:09

Aravind