[英]Passing dynamic functions from parent component to grandchild component Angular
[英]Angular 2+: Communicate between grandchild directive (dynamic component host) and SPECIFIC parent component using Subjects (provide context)
我是Angular 2+的新手,我正面臨一個瑣碎的情況,我似乎找不到出路。
我有一個父組件(parent.component.html),其中包含通過迭代呈現的組件列表(item.component.html),如下所示:
parent.component.html
<child-item-component *ngFor="let date of shift?.dates" [shift]="shift"
[dragEnabled]="dragEnabled"></child-item-component>
child-item.component.html
<li [contextMenuTrigger]="contextMenuData">
<ng-template contextMenuHost></ng-template>
</li>
每個子組件都有一個<li>
元素,並附加了一個[contextMenuTrigger]
指令。 該指令包含用於注入動態組件的邏輯,該動態組件是具有與該事件無關的不同動作的工具提示。
當用戶單擊包含指令( <li>
)的元素時,將呈現動態組件。
嘗試通過@Output()
從指令向組件發出事件失敗后,我最終通過雙向服務使用Subjects在發生單擊時通過父母與孩子之間進行通信。
需求
我需要將<child-item-component>
上的[dragEnabled]
設置為false。
問題
我可以將該布爾值傳遞給父級,但是我只需要對特定的父級項執行操作,該父級項剛剛注入了動態組件,因此在打開工具提示時該特定項不可拖動,但是其余的還是。 基本上,我需要一種為主題提供上下文的方法,以便可以識別從其各自的<child-item-component>
中的哪個[contextMenuTrigger]
指令觸發了該事件,否則,所有項目組件都將接收該事件。並且它們都同時將[dragEnabled]
為false,而沒有機會區分它們。
我一直在環顧四周,看不到有人在這里遇到同樣的情況,所以我想知道我做錯了什么。
希望我足夠清楚。 提前謝謝大家。
嘗試記住使用click指令在child-item-component組件內被單擊。
像這樣:
TS文件
// I guess this is something similar to your Subject-Solution
@Input() dragEnabled: Subject<boolean> = new Subject();
// your memory of being clicked
private isClicked: boolean = false;
...
constructor(){
this.dragEnabled.subscribe( () => {
this.onDragEnabledEvent();
});
}
private clicked(): void {
this.isClicked = true;
}
...
// this method is triggered by your Subject out of the subscription
// only the clicked element is blocked all the others get unblocked
onDragEnabledEvent(): void {
if(this.isClicked) {
this.isClicked = false; // reset
// YOUR BLOCKING CODE GOES HERE
} else
// YOUR UNBLOCKING CODE GOES HERE
}
}
HTML模板
<child-item-component *ngFor="let date of shift?.dates" [shift]="shift"
[dragEnabled]="dragEnabled" (click)="clicked()"></child-item-component>
dragEnabled
請注意,主題僅在內容更改時才會觸發新事件。 由於內容本身對您不感興趣,因此建議您采取以下措施:
將當前日期作為UTC時間戳字符串發送
subject.next(new Date().getTime());
這將始終帶有新值,並且您的訂閱將始終觸發。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.