簡體   English   中英

兄弟組件未從子組件獲取更新的參數值 - Angular

[英]Sibling component is not getting updated parameter value from child component - Angular

我有父、子和兄弟組件。 當我們更改子組件中的參數值時。 兄弟組件方法應該觸發並且更新的值應該得到。

我的問題是,我能夠觸發從父組件到兄弟組件的方法,但在觸發時沒有獲得更新的值。 有一些延遲。

我使用兩種不同的方法來傳遞參數和觸發方法,這可能是問題。 請幫忙。

當 zip 代碼從子組件更改但未在觸發時在兄弟組件處獲取 zip 代碼值時,此方法從父組件觸發。

getSiblingSettingFn() {

}

子組件

@Component({
    selector: 'child-cmp',
    template: '<p>child</p>'
})
class ChildCmp {
    @Output() childGInParameters = new EventEmitter<{ city: string, state: string, zip: string }>();

    city: any = "Palmdale";
    state: any = "CA";
    zip: any = "93551";

    setGeneralInfo() { // on change event
        this.childGInParameters.emit({ city: this.city, state: this.state, zip: this.zip });
    }
}

父組件

import { SiblingComponent } from '../SiblingComponent';
@Component({
    selector: 'parent-cmp',
    template: '<child-cmp (childGInParameters)="getGeneralInfo($event)" > </child-cmp>
                <br/>
                <sib-cmp [zip]="zip" [state]="state" [city]="city" ></sib-cmp>'
})
class ParentCmp {
    @ViewChild('SiblingComponent') sibchild: SiblingComponent;

    getGeneralInfo(childGInParameters: any) {
        this.city = childGInParameters.city;
        this.state = childGInParameters.state;
        this.zip = childGInParameters.zip;

        this.sibchild.getSiblingSettingFn();
    }
}

兄弟組件

@Component({
    selector: 'sib-cmp'
})
class SiblingComponent {
    @Input() zip: any;
    @Input() state: any;
    @Input() city: any;

    ngOnChanges(changes: SimpleChanges) {
        const c: SimpleChange = changes.zip;
        this.zip = c.currentValue;
    }

    getSiblingSettingFn() {
       
    }
}

試試這個,它應該工作

 ngOnChanges(changes: SimpleChanges) { if(changes.zip.previousValue){ this.zip = changes.zip.currentValue; } }

使用 Service 與父子直接關系以外的不同組件進行交互。 因此,您可能需要在父組件級別和兄弟組件級別之間工作的服務。

  • 從父級到子級共享數據:@Input
  • 從孩子到父母共享數據:@ViewChild
  • 從子級到父級共享數據:@Output 和 EventEmitter
  • 在各種組件之間共享數據:服務

參考組件交互 - https://www.calibraint.com/blog/angular-components-interaction-methods

暫無
暫無

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

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