Angular 2+ ngOnChanges与eventEmitter

时间:2017-11-28 15:17:35

标签: angular eventemitter ngonchanges

我在同一个父母中有两个组件。当我单击组件1中的按钮onSubmit()时,它会向将submittedPayment存储事件的父母发出事件processingPayment,然后组件2将通过父母接收此事件。然而,组件2具有与接收的事件发射冲突的ngOnChanges的功能。当我点击onSubmit()时,控制台会显示错误"无法读取属性' currentValue'未定义"在ngOnChanges函数中。如果我删除此事件发出指令[disabledCancelBtn]="processingPayment",代码工作正常,但组件2不接收该单击操作的事件。

这是我的代码:

组件1:

export class Component1 implements OnInit {

  @Input() openTransaction = <Transaction>{};
  @Output() submittedPayment = new EventEmitter<boolean>();

  submitted: boolean = false;
  disabledSubmitButton: boolean = false;  

  constructor() {}  

  onSubmit(formValues: any) {
    this.submitted = true;
    this.disabledSubmitButton = true;
    this.submittedPayment.emit(true);
    console.log(formValues);
  }

  ngOnInit() {}
} 

组件2:

export class Component2 implements OnInit, OnChanges {

  @Input() openTransaction = <Models.Transaction>{};
  @Input() disabledCancelBtn: boolean = false;
  @Output() onUpdateTransaction = new EventEmitter<Models.Transaction>();
  editableBtc: any;
  editableUsd: any;
  editingBtc: boolean = false;
  editingUsd: boolean = false;
  cancelling: boolean = false;

  constructor(
    public timerService: RateTimerService,
    @Inject(PLATFORM_ID) private platformId: Object
  ) { }

  ngOnInit() { }

  ngOnChanges(changes: SimpleChanges) {
    if (isPlatformBrowser(this.platformId)) {
      if (changes.openTransaction.currentValue !== undefined) { // ERROR HERE 
        this.editableBtc = this.openTransaction.btcAmount;
        this.editableUsd = this.openTransaction.total;

        const timeLeft = moment.utc(this.openTransaction.validUntil).diff(moment.utc(Date.now()), 'seconds');
        this.timerService.startRestart(timeLeft);
      }
    }
  }
}

父母组成部分:

export class ParentsComponent implements OnInit {

  openTransaction: Models.Transaction;

  processingPayment: boolean = false;

  constructor(private apiService: ApiService,
    @Inject(PLATFORM_ID) private platformId: Object) {
  }

  ngOnInit() {
    if (isPlatformBrowser(this.platformId)) {
      this.apiService.openTransactions()
        .subscribe(
        (pending: Models.Transaction[]) => {
          this.openTransaction = pending[0];
        },
        (err) => console.log('Error fetching Pending transactions: ', err));
    }
  }
}

家长观点:

<div class="col-sm-12 col-md-6 payment-section">
      <app-component1  [openTransaction]="openTransaction"
                            (submittedPayment)="processingPayment = $event">
      </app-component1>
    </div>

    <div class="col-sm-12 col-md-6 summary-section">
      <app-component2 [disabledCancelBtn]="processingPayment"
                      [openTransaction]="openTransaction">
      </app-component2>
    </div>

1 个答案:

答案 0 :(得分:1)

changes参数包含已更改的属性。因此,当仅processingPayment属性更改时,您无法期望changes.openTransaction被定义。