我在同一个父母中有两个组件。当我单击onSubmit()
组件 1 中的按钮时,它将向将事件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>