1

im trying to implement Routing in my programm. The basic routing works if i type in the URL in the browser. However if i want to use my button from the MainComponent Im getting an error:Cannot read property 'loadFromJson' of undefined.

Before I implemented the Router it just worked fine like it is now.

My app-routing.module:

...
const appRoutes: Routes = [
{ path: 'start',        component: FrontPageComponent },
{ path: 'action',        component: MainComponent },
{ path: '',   redirectTo: '/start', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
  ];
...

My Main component calls a function with a button. Part of the function however calls another function which is in the child component.

MainComponent.html:

  <button routerLink="/action" type="submit" (click)="function()" >Load</button>
   ..
   ..
  <router-outlet></router-outlet>

MainComponent.ts

@ViewChild(ChildComponent) childComponent; <--imported ChildComponent with @ViewChild
      ...
      function(): void { 
        this.DownloadService.downloadResource(this.url).subscribe(
          json => this.childComponent.loadFromJson(json, this.url),   <--function from childComponent
          err => this.setError(err),
        );
      }

Function in the child Component:

childComponent.ts:

 private loadFromJson(json: any, id: string): void {
   this.initEmptyContainer();
   this.addFromJson(json, id);
}
 ...

Why cant it read the property and what can I do to fix it?

pattplatt
  • 63
  • 8

2 Answers2

0

To refer a class variable inside your method use this.childComponent

Try this

@ViewChild(ChildComponent) childComponent;

...

function(): void { 
    this.DownloadService.downloadResource(this.url).subscribe(
      json => this.childComponent.loadFromJson(json, this.url),   // <-- Refer your childComponent using this
      err => this.setError(err),
    );
}
Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78
0

the view queries are set before the ngAfterViewInit callback is called.

@ViewChild(ChildComponent) childComponent;

 downloadResource (): void { 
  this.DownloadService.downloadResource(this.url).subscribe(
     json => this.childComponent.loadFromJson(json, this.url),
          err => this.setError(err),
        );
      }

 ngAfterViewInit(): void {
    this.downloadResource();
  }

check here for more details

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91