Angular:从父级成功调用后,数据未传递给子组件

问题描述 投票:0回答:2

我有一个父子组件。

在子组件中,我有一个按钮,如下所示。

//child.component.html

<button mat-raised-button  [disabled]="!form.valid || submitButtonDisable" type = 'Submit' color='primary'  >
{{generateButton}}
</button>


//child.component.ts
@Output() onGenerateReport: EventEmitter<any> = new EventEmitter<any>();
@Input() generateButton: String;

OnSubmit() {
  this.onGenerateReport.emit(this.parameterRequest);  // paasing data to parent after button click
  this.submitButtonDisable = true;
  this.generateButton = 'Generating...'
  }

以下是父组件

  // parent component.html

  <child-component
      (onGenerateReport)="handleGenerateReport($event)"
      [generateButton] = "generateButton | async">
  </child-component>

    //parent.component.ts
 generateButton: Observable<String >;

   handleGenerateReport($event: ParameterRequest) {  //  event trigerred

        this.store.dispatch(new fromStore.SendRequest($event));

    this.store.select(fromStore.isDataLoaded).pipe(take(1)).subscribe(data => {
    if(data) {
    this.generateButton = of('Generate');   // this data not passing to child
   }
 })
}

成功调用后,我将数据传递给子,以更改按钮的标签。

但是ngrx选择,数据没有传递给孩子。我错过了什么吗?

angular typescript button parent-child ngrx
2个回答
2
投票

您需要对子项使用ngOnChanges来检测父项的更改。您需要在子组件中使用以下代码。

import { OnChanges, SimpleChanges } from '@angular/core';
class childComponent implements OnChanges, OnInit, AfterViewInit {    
//child.component.ts
@Output() onGenerateReport: EventEmitter<any> = new EventEmitter<any>();
@Input() generateButton: String;

ngOnChanges(changes: SimpleChanges): void { 
  if(changes != null) {
    console.log(changes);   // here in changes object you will get the updated value of your input variables ex:  generateButton  
  }        
}

OnSubmit() {
   this.onGenerateReport.emit(this.parameterRequest);  // paasing data to parent after button click
   this.submitButtonDisable = true;
   this.generateButton = 'Generating...';}}

0
投票

只需执行以下步骤即可

  • 只需导入import { Input, OnChanges, SimpleChanges } from '@angular/core';包。
  • 然后实现接口export class ComponentName implements OnChanges
  • 然后只需创建函数ngOnChanges(changes: SimpleChanges){ // changes.your input property name (contains the old and the new value) // here you can getting all @Input property changes. }
© www.soinside.com 2019 - 2024. All rights reserved.