• 主页
  • Angular 2+ ngOnChanges与eventEmitter冲突

Angular 2+ ngOnChanges与eventEmitter冲突

我在相同的父级中有两个组件。当我点击component 1中的按钮onSubmit()时,它会向parents发出一个event submittedPayment,parents将事件存储到processingPayment中,然后component 2将通过parents接收该事件。然而,组件2具有与接收到的事件发送冲突的ngOnChanges功能。当我点击onSubmit()时,控制台显示错误"Cannot read property 'currentValue‘of undefined“in ngOnChanges function。如果我删除这个发出指令[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>

转载请注明出处:http://www.sh-shangchao.com/article/20230526/1060737.html