@ViewChild always returns undefined

前端 未结 3 634
北恋
北恋 2021-02-13 14:36

I know this has been asked before, but none of the selected answers are working for me.

I am trying to use @ViewChild to get my ng-select from t

相关标签:
3条回答
  • 2021-02-13 14:39

    In my case, I encountered the same problem. I console.log()-ed the content that is retrieved from the child component and it gives me 'undefined'.

    And I solved it by merely refreshing the page. ctrl+shift+R may help. I guess it's because the cache of the browser that leads to this problem.

    0 讨论(0)
  • 2021-02-13 14:41

    @twaldron Are you using some delayed data loading in ngOnInit?

    Because in that case, in my experience, reading a @ViewChild as a ElementRef produces no results

    If your component has the data already resolved (like the case when a parent passes a child data object to a sub component) it should work (at least for me it did).

    In the case of asynchronous data loading, the way I was able to make it work is using a change notification

     @ViewChildren('userSelect') userSelect: QueryList<ElementRef>;
    
     ngAfterViewInit(): void {
        this.userSelect.changes.subscribe(item => {
            if (this.userSelect.length) {
                alert(this.userSelect.first.nativeElment.outerHTML)
            }
        })
     }
    
    0 讨论(0)
  • 2021-02-13 14:46

    I replaced all occurrences of

    *ngIf="flag"
    

    with

    [style.display]="flag ? 'block' : 'none'"
    

    to get this to work consistently in my case. Otherwise the ViewChild components that didn't exist when my view first loaded would potentially remain undefined for ever.

    0 讨论(0)
提交回复
热议问题