How to reload the current Angular 2 Component

Dave picture Dave · Nov 5, 2016 · Viewed 35.6k times · Source

How can I reload the same component again in Angular 2?

Here is my code below:

import { Component, OnInit, ElementRef, Renderer } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { productModel } from '../_models/index';
import { categoryListService } from '../_services/index';

@Component({
  selector: 'app-product',
  templateUrl: 'product.component.html',
  styleUrls: ['product.component.css']
})
export class productComponent implements OnInit {
  uidproduct: productModel;
  param: number;
  constructor(
    private elementRef: ElementRef,
    private route: ActivatedRoute,
    private router: Router,
    private categoryListService: categoryListService) { }

  ngOnInit() {
    this.route.params.subscribe(product => {
      console.log('logging sub product obj', product);
    });
    this.uidproduct = JSON.parse(sessionStorage.getItem('product'));
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = "http://this/external/script/needs/to/be/loaded/each/time.js";
    this.elementRef.nativeElement.appendChild(s);
  }
  nextproduct(){ 
    let i = this.uidproduct.order;
    this.categoryListService.findNextproduct(this.uidproduct);
    this.param = ++i;
    this.router.navigate([`/product/${this.param}`]);
  }
}

nextproduct() is bound to a click event in the template.

The uidproduct is a JSON object that has a number of properties and i'm updating the DOM with {{uidproduct.classname}}

I'm using this in the template like this:

<div id="selected-product" class="{{uidproduct.classname}}">

When I click the <button (click)="nextproduct()"> it will change the class property in the DOM but I need to reload the component for the external script to have effect.

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Feb 21, 2017

You can use *ngIf to re-render the content of a template:

@Component({
  selector: '...',
  template: `
<ng-container *ngIf="!rerender">
 template content here
</ng-container>`
})
export class MyComponent {
  rerender = false;
  constructor(private cdRef:ChangeDetectorRef){}
  doRerender() {
    this.rerender = true;
    this.cdRef.detectChanges();
    this.rerender = false;
  }
}