簡體   English   中英

角度:從父級成功調用后,數據未傳遞到子級組件

[英]Angular: Data not passing to child component after success call from parent

我有一個父子組件。

在子組件中,我有一個按鈕,如下所示。

//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選擇, 數據不會傳遞給child 我有什么想念的嗎?

您需要在子級上使用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...';}}

只需執行以下步驟

  • 只需import { Input, OnChanges, SimpleChanges } from '@angular/core';導入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. } ngOnChanges(changes: SimpleChanges){ // changes.your input property name (contains the old and the new value) // here you can getting all @Input property changes. }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM