簡體   English   中英

當指令在帶有異步 pipe 的 ngIf 中時,如何獲取指令的 ViewChildren

[英]How can I get ViewChildren of a Directive when it is inside an ngIf with async pipe

我有一個組件,它基於帶有異步 pipe 的 observable 呈現其內容。

<div *ngIf="equipment$ | async as equipment">
  <button myDirective></button>
</div>

在 .ts 文件中,我得到了所有的 MyDirective 孩子。 可以有任何數字。

@ViewChildren(MyDirective) actions!: QueryList<MyDirective>;

然后我想在 ngAfterViewInit 中訪問它。

ngAfterViewInit(): void {
  console.log(this.actions)
}

這會記錄一個包含 0 個項目的 QueryList。 如果我將指令放在我的 async pipe 之外,它一切正常:

<div *ngIf="equipment$ | async as equipment">
  // Some HTML here
</div>
<button myDirective></button>

有什么方法可以檢索嵌套在異步 pipe 下的指令? 我需要保留 ngIf,因為我將輸入綁定到設備變量(包含屬性)。

編輯:

所以,想來想去,我意識到我在這里要做的是重新創建 NgRx。 經過這么長時間認為它太復雜了,我現在明白了它帶來的所有好處和它解決的問題。 我要提前 go 並嘗試實現它!

您需要添加static: false因為它是動態呈現的組件:

@ViewChildren(MyDirective, { static: false }) actions!: QueryList<MyDirective>;

但是您不能確定該指令在 ngAfterView init 中是否可用。 因為equipment$可能需要一些時間...

也許你可以在 observable 中添加一個tap()並在那里做你的console.log()

您可以創建一個隱藏指令,讓我解釋一下:

    @Input() hide: boolean;

constructor(private renderer: Renderer2, private elRef: ElementRef) {
}

ngOnChanges() {
    if (this.hide) {
        this.renderer.setStyle(this.elRef.nativeElement, 'visibility', 'hidden');
    } else {
        this.renderer.setStyle(this.elRef.nativeElement, 'visibility', 'visible');
    }
}

因為 hide 指令不會在 dom 上顯示元素,但它仍然可以訪問

西蒙,執行指令時,您無法訪問不在屏幕中的元素。

當然你不能在 afterViewInit 中訪問,因為條件仍然是假的。 所以,你有兩種方法

  1. 根據您的創建一個可觀察的並使用 rxjs 操作員點擊

    equipmentDone$=this.equipment$.pipe( tap((res:any)=>{..here you has yet your this.actions... //it's possible, I'm not pretty sure you need enclosed in a setTimeout setTimeout(()=>{..here sure, sure you has this.actions.. }) }) )

    並使用

    <div *ngIf="equipmentDone$ | async as equipment"> <button myDirective></button> </div>
  2. 訂閱 QueryList 的可觀察變化

    ngAfterViewInit(){ this.actions.changes.subscribe(res=>{..here you has your actions.. }) }

暫無
暫無

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

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