Angular 2 : Component Interaction, 可选输入参数

标签 angular angular2-components

我有一个实现,其中父级希望通过使用子组件可用的 @Input 参数将某些数据传递给子组件。但是,此数据传输是可选的, parent 可能会或可能不会根据要求传递它。组件中是否可以有可选的输入参数。我在下面描述了一个场景:

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

}

最佳答案

您可以使用 ( ? ) 运算符,如下所示

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

}

使用子组件的父组件会是

@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

关于Angular 2 : Component Interaction, 可选输入参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39717083/

相关文章:

Angular2 RC5 路由器 3.0.0 - 共享库组件中的 <a> 中没有 href

asynchronous - TypeScript/Angular 2 - 在另一个完成后调用一个函数

typescript - 如何在角度2的输入文本变化时调用函数

angular - 如何在 Angular 2 单例中制作组件?

Angular 2指令错误

angular - 如何使用 ResolveComponentFactory() 但使用字符串作为键

Angular CLI(v.1.0.1) 不允许用于开发目的的子域 : Invalid Host Headers

angular - 双向 Angular 绑定(bind)中的 ExpressionChangedAfterItHasBeenCheckedError

css - 如何使用自定义 css 样式覆盖 ng2-bootstrap Accordion 默认样式