Angular 6 @Viewchild is not working with lazy loading

  • A+
Category:Languages

Here is my code that gives error cannot read property title undefined.

Parent Component

import { Child } from './child.component'; @Component({   selector: 'parent', }) export class ParentComponet implements OnInit, AfterViewInit {  constructor(){}    @ViewChild(Child) child: Child;    ngAfterViewInit(){     console.log("check data", this.child.title)   } } 

And Child Component is.

@Component({       selector: 'child',     })     export class ChildComponet {       public title = "hi"      constructor(){}      } 

routing.module.ts is like

{         path: "",         component: ParentComponent,         children: [             {                 path: '/child',                 component: ChildComponent             }         ] } 

And Gives error is

ERROR TypeError: Cannot read property 'title' of undefined(…) 

 


I think you are missing 'template' or 'templateUrl' in relevance to creating a Component

ParentComponent

import { ChildComponent } from './child.component';    // {ChildComponent} not {Child} as we are referencing it to the exported class of ChildComponent  @Component({    selector: 'parent',    template: `<child></child>` }) export class ParentComponet implements OnInit, AfterViewInit {...} 

ChildComponent

@Component({   selector: 'child',   template: `<h1>{{ title }}</h1>` }) export class ChildComponent {...}       // Be sure to spell it right as yours were ChildComponet - missing 'n' 

UPDATE as per the user's clarification on this thread

Had added a Stackblitz Demo for your reference (Check the console)

If you want to access the ChildComponent that is rendered under the Parent Component's you can do so by utilizing (activate) supported property of router-outlet:

A router outlet will emit an activate event any time a new component is being instantiated

Angular Docs

ParentComponent's Template

@Component({    selector: 'parent',    template: `<router-outlet (activate)="onActivate($event)"></router-outlet>` }) export class ParentComponent {      onActivate(event): void {         console.log(event);         // Sample Output when you visit ChildComponent url                                     // ChildComponent {title: "hi"}          console.log(event.title);   // 'hi'      }  } 

The result will differ based on the visited page under your parent's children

If you visit Child1Component you will get its instance Child1Component {title: "hi"}

If you visit Child2Component you will get its instance Child2Component {name: "Angular"}

These results will then be reflected on your ParentComponent's onActivate(event) console for you to access

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: