簡體   English   中英

在不使用選擇器的情況下在另一個組件中使用局部組件變量

[英]use a local component variable in another component without using selector

我在 angular 中有一個名為first_component的組件。 我在其 HTML 中使用另一個名為second_component的組件,例如:

<second_component [addChildMode]='addChildMode' [defaultValues]='defaultValues' [chosenRelationIsInitialRelation]='chosenRelationIsInitialRelation'></second_component>

如您所見,我使用@Input()將一些值從 first_component 傳遞到 second_component,例如addChildModedefaultValues等。 (因為我將 second_component 與選擇器一起使用,所以我可以使用@Input() )。 現在我有一個showValue ,它是 second_component 中的一個局部變量,我想知道它的變化,因為我沒有通過它的選擇器使用 first_component,我怎么能注意到showValue在第二個組件中發生變化? ps first_component 和 second_component 只是兄弟姐妹。 (不是孩子和父母)

由於您需要對跨多個組件的showValue的變化做出反應,因此它不再(不應該)是本地的。 如果使用NgRX或者類似state管理,可以把showValue放在一個store中。 當該變量具有全局意義時,我才推薦這樣做。

但由於這聽起來更像是一對組件在或多或少的本地環境中緊密合作,我建議使用共享服務,它將showValue的值保存在一個可觀察的對象中,這兩個組件可以推送/訂閱。

我的建議是使用 ChangeDetectionStrategy,如果不是那么必要,或者如果您沒有任何其他方式,那也是如此。

使用 state 管理對於大型項目會很好,但如果用於較小的項目會使應用程序變得沉重。

暫無
暫無

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

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