Search code examples
angularangular2-components

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() { }

}

Solution

  • 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