簡體   English   中英

如何將 object 從父組件傳遞到子組件作為參考

[英]How to pass object from parent to child component as reference

我的應用程序確實存在問題,當我將 object 從父組件傳遞到子組件時,我正在傳遞此 object 的副本。 並且此副本上的所有操作都不會更改原始 object。 所以也許作為一個例子:

export class ParentComponent { 
    model: any;

    sendToDb(){
        someService(this.model);
    }
}

來自 html 的片段

<ChildComponent [model]="model"> </ChildComponent>

子組件:

export class ChildComponent { 
    @Input() model: any;

    someChangesOnAction(){
        this.model.name = "test";
    }
}

因此,每當ChildComponent修改model並且在該父級想要將此 obj 發送到后端時,它都使用原始對象。 這是一種簡單/干凈的方法嗎? 也許我對這個問題使用了不好的方法。

嘗試使用 Angular 文檔中所示的雙向數據綁定: https://angular.io/guide/two-way-binding

所以你的代碼看起來像這樣:

<ChildComponent [(model)]="model"> </ChildComponent>

暫無
暫無

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

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