Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reload the current Angular 2 Component

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.

like image 737
Dave Avatar asked Nov 05 '16 16:11

Dave


People also ask

How do I reload a component in Angular 2?

In your component, import NavigationEnd: import { Router, NavigationEnd } from '@angular/router'; And then subscribe to it in your constructor: constructor(private thingService: ThisThingService, private router: Router) { router.

How do you reload the current component in Angular 6?

Angular will reload page which means Page Component/Resolvers/Guards in specific way. using this. router. onSameUrlNavigation = 'reload';

How do you refresh a component from another component in Angular 12?

To refresh, or better to say update another component from a different component, we can use the concept of Observables and Subject (which is a kind of Observable). This concept has an added benefit when data are to be received from APIs for CRUD operations.

How do I reload components in Angular 9?

There is button by which i am updating my page data. on button click i have save data in back end and refresh data. So to reload/refresh the component - as per my requirement - is only to refresh the data. if this is also your requirement then use the same code written in constructor of component.

How to reload or refresh a component in angular?

Refresh a component on a button click; Reload a component data on delete; In Angular, page navigation can be done with or without angular router module. Let’s discuss how to reload or refresh component in Angular in multiple ways. refresh with windows.location.reload. In Angular also Page can be reload with windows.location reload

How to reload entire page using router in angular?

One is to use window.reload to reload entire page, and the other is to use onSameUrlNavigation-reload refresh component with an angle router. Some times, As a developer, you need to write a logic to reload a component or a page for a below cases In Angular, page navigation can be done with or without angular router module

What is the difference between page refresh and refresh window in angular?

In typescript component - app.component.ts As window is an global object which can be reused directly in Angular components. Moving from one page to another in a legacy web application reloads the page and its content. Page refresh, on the other hand, reloads the whole page.

Which is not a known element in Angular 2?

Angular 2 'component' is not a known element 1 Refresh one Component on click event of Another Component in Angular Hot Network Questions How do you distinguish "Substantiv + nach" from "after" in German?


2 Answers

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;
  }
}
like image 194
Günter Zöchbauer Avatar answered Oct 20 '22 19:10

Günter Zöchbauer


I don't understand why you need to reload the component. If you're binding to the various fields of uidproduct, then reloading that should refresh the values shown in the component. So reloading the component does nothing but add overhead.

If there is a terrific reason not mentioned here why you think you still need to do this, then here is what you do:

  1. Navigate to another (possibly blank) component.
  2. Navigate directly back.

The problem is that you need to wait for the first navigation to finish before doing the second one.

In your component, import NavigationEnd:

import { Router, NavigationEnd } from '@angular/router';

And then subscribe to it in your constructor:

constructor(private thingService: ThisThingService, private router: Router) { 
   router.events.subscribe(event => {
    if (event instanceof NavigationEnd) {
      if (event.url === '/blank') {
        this.router.navigate(['product']); 
      }
    }
  });

Notice that I wait for NavigationEnd to happen and then check to see I was routing to my blank component. If it is the blank component's path, I navigate back to the product. If you really need to pass that ID, just store it on your object and add it here.

Instead of routing to your product page in nextproduct(), navigate to blank.

this.router.navigate(['blank']);

And that should reload your component perfectly fine.

The problem I intentionally left in for simplicity, is that the subscribe call in the constructor will execute for every reload. So as an exercise to the reader, take it out of the constructor and create a nice service for it, or move it to the constructor of your app component, or maybe to your routing module or wherever makes sense to you.

like image 41
Cobus Kruger Avatar answered Oct 20 '22 20:10

Cobus Kruger