Angular2:交换子组件

时间:2017-03-17 11:56:38

标签: angular rxjs

我尝试使用ngIf替换子组件,如:

<div *ngIf="paymentListShow" payment-list></div>
<div *ngIf="paymentFormShow" payment-form></div>

因此,我的父组件旨在处理这些值:

swapComponent(componentName: string): void {
    let paymentState = {
      'paymentList': (that): void => {
        that.paymentFormShow = false;
        that.paymentListShow = true;
      },

      'paymentForm': (that): void => {
        that.paymentListShow = false;
        that.paymentFormShow = true;
      }
    };

    paymentState[componentName](this);
}

交换子组件是否存在更优雅的方式?使用rxjs Observables?

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

当然不是最好的,但这可能是一种更清洁的方式:

show = {
  paymentList: true,
  paymentForm: false
}

swapComponent(componentName: string): void {
  for (const component in this.show) {
    if (this.show.hasOwnProperty(component)) {
      this.show[component] = (component === componentName) ? true : false;
    }
  }
}

结合:

<div *ngIf="show.paymentList" payment-list></div>
<div *ngIf="show.paymentForm" payment-form></div>