Angular 2: Component Interaction, optional input parameters

前端 未结 3 2037
半阙折子戏
半阙折子戏 2021-02-06 20:39

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

相关标签:
3条回答
  • 2021-02-06 20:46

    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

    0 讨论(0)
  • 2021-02-06 20:49

    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() { }
    }
    
    0 讨论(0)
  • 2021-02-06 21:05

    You have two options here.

    1) You can use an *ngIf on the child in case the child does not need to be displayed when its Input is empty.

     <parent>
        <child *ngIf="true" [showName]="true"></child> //passing parameter
        <child></child> //not willing to passing any parameter
    </parent>
    

    2) In case the child should get displayed without any input, you can use a modified setter to check for the presence of input variables`

    In the child.ts:

    private _optionalObject: any;
    @Input()
    set optionalObject(optionalObject: any) {
        if(optionalObject) this._optionalObject = optionalObject;
    }
    get optionalObject() { return this._optionalObject; }
    
    0 讨论(0)
提交回复
热议问题