Anonymous
Anonymous

Reputation: 1

Cannot read property 'nativeElement' of undefined @viewchild

here is the scenario, i have main file tabs component where i have included text component using @ViewChild(); now on ngAfterViewInit() i am initializing menu and list of submenu. and as soon as i am done creating list of submenu i want to assign them to text component. so that when user clicks on text component he will be seeing subcomponents assigned by tabs component.

ngAfterViewInit() {
    // menu initialization
    // sub-menu initialization
    this.tabTextComponent.nativeElement.selectedSubTabs = this.selectedSubTabs;
}

i have tried both with and without element ref but nothing works. i have also visited other solutions but nothing works for me. can anyone help me?

Upvotes: 0

Views: 362

Answers (1)

codequiet
codequiet

Reputation: 1242

It may be a problem with how you're defining this.tabTextComponent. Try this (assuming the class of your component is TabTextComponent):

@ViewChild(TabTextComponent) tabTextComponent: TabTextComponent;

ngAfterViewInit() {
    // this.tabTextComponent should be defined here
    this.tabTextComponent.selectedSubTabs = this.selectedSubTabs;
}

Also note that you don't need to use nativeElement unless you're trying to do something with the DOM. If selectedSubTabs is a non-private property of the TabTextComponent class, you can access it directly.

(By the way, it looks like you're trying to set a property of the child component from the parent? You might consider using an @Input binding instead.)

Upvotes: 1

Related Questions