簡體   English   中英

Angular 10 - 無論靜態屬性如何,都啟用 ViewChild 獲取實例

[英]Angular 10 - Enable ViewChild to get instance regardless of static property

是否有一些方法@ViewChild裝飾讓孩子組件的實例在ngOnInit從老同@ViewChild角6?

我試過類似的東西:

@Component({
  ....
})
export class AppComponent implements OnInit {
  @ViewChild(HelloComponent, {static: true})
  @ViewChild(HelloComponent, {static: false})
  hello: HelloComponent;

  ngOnInit() {
      console.log('Hello Instance',this.hello);
  }
}

但它導致我錯誤說同一成員不允許使用多個裝飾器

嘗試這個:

static: true

因此,根據經驗,您可以執行以下操作:

{ static: true }當你想在 ngOnInit 中訪問 ViewChild 時需要設置。

{ static: false }只能在 ngAfterViewInit 中訪問。 當你有一個結構指令時,這也是你想要的

我想分享我剛剛為@ViewChild 發現的其他讀者知識

讓@ViewChild 在ngOnInit static屬性設置為 false

我必須像這樣把它放在 setTimeout() 里面:

@ViewChild(HelloComponent, {static:false}) hello: HelloComponent;

ngOnInit() {
    setTimeout(() => {
        console.log('Hello Instance',this.hello);
    }, 100);
}

這樣,它就可以在ngOnInit獲取子組件

暫無
暫無

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

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