Angular4, update component on route change

1.3k views Asked by At

How to update component when route changes. I have this component :

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ListService } from '../list/list.service';

@Component({
  selector: 'view',
  template: `
    <div *ngIf="!entity">
    <p>Select <b (click)="showRow()">row {{entity}}</b>!</p>
    </div>
    <div *ngIf="entity">

      <p >{{entity.id}}</p>
      <p >{{entity.name}}</p>
      <p >{{entity.weight}}</p>
      <p >{{entity.symbol}}</p>
    </div>
  `,
  styles: []
})
export class ViewComponent implements OnInit {

  constructor(
    private route: ActivatedRoute,
    private service: ListService
  ) {
    this.route.params.subscribe(params => {
      const id = parseInt(params['id']);
      if (id) {
        const entity = this.service.getRow(id);
        this.entity = entity
      }
    });
  }

  entity;

  showRow() {
    console.log(this.entity);
  }

  ngOnInit() {
  }
}

in this.entity inside constructor i have desired object but when i execute showRow this.entity is undefined, what i'm doing wrong ? I have tried to change property to different name, and it didn't work as expected, if any one knows how to resolve this or point me to right direction.

EDIT: getRow from service

getRow(id) {
  console.log(id, 'test');
  return this.datasource.find(row => row.id === id);//returns good row
}
3

There are 3 answers

0
Viszman On

I found answer to my problem, i just needed to put router-outlet in template just like that :

....
....
template: `
  <router-outlet>
    <div *ngIf="row?.id; else elseBlock">
    <div>
      <p>{{row.id}}</p>
      <p>{{row.name}}</p>
      <p>{{row.weight}}</p>
      <p>{{row.symbol}}</p>
    </div>
    </div>
  </router-outlet>
`,
0
HD.. On

Move your code to ngOnInit() method and check will you get value or not.

  ngOnInit() {
    this.route.params.subscribe(params => {
     const id = parseInt(params['id']);
     if (id) {
         const entity = this.service.getRow(id);
         this.entity = entity
     }
   });
 }
0
KuroKyo On

I believe you need to define/initialize the entity that is positioned above showRow, such as:

const entity = Entity;

or something along those lines. apologies I am quite new to angular as well.