Tips for refreshing the current Angular 2 Component

I'm looking for a way to refresh the same component in Angular 2. Can anyone provide guidance?

Below is the code snippet I have:

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() method is triggered by a click event in the template.

The uidproduct represents a JSON object with various properties and I'm updating the DOM using {{uidproduct.classname}}

In the HTML template, it's used like this:

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

Whenever I click the

<button (click)="nextproduct()">
, the class property in the DOM changes but I need to reload the component for the external script to take effect.

Answer №1

If you want to update the content of a template, you can utilize the *ngIf directive:

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

Answer №2

Why is there a need to constantly reload the component? If you have bound the fields of uidproduct, then simply refreshing that should update the values displayed in the component. Reloading the component only adds unnecessary overhead.

If you still feel there is a valid reason for reloading, follow these steps:

  1. Go to another component, even a blank one.
  2. Immediately navigate back to the original component.

The key is to ensure that the first navigation is completed before proceeding with the second.

In your component, include NavigationEnd:

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

Then subscribe to it inside the constructor:

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

Note that I wait for NavigationEnd event and check if I am navigating to the blank component's path. If so, I redirect back to the product component. If passing an ID is necessary, store it on the object and include it here.

Instead of directing to the product page in nextproduct(), redirect to blank.

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

This method should effectively reload your component. An issue to consider is that the subscribe call in the constructor will run every time the component is reloaded. As a challenge, try removing it from the constructor and creating a dedicated service for it, or incorporating it into the app component's constructor, routing module, or any other appropriate location.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Prevent JSON.parse() function from stripping away any trailing zeros in a JSON string dataset

After creating a JSON string, I encountered an issue where the values were not being parsed correctly. Here is the code snippet: <script> var string = JSON.parse('{"items":[{"data":[5.1]}, {"values":[5.10]}, {"offer":[3.100]}, {"grandtotal":[12 ...

Updating chart.js data seems to be presenting some challenges

Need help fetching data with an AJAX request to update chart.js. The AJAX request is working fine, but the response doesn't update the chart. This is how I fetch the data: <script type="text/javascript"> $(document).ready(function(){ $("#da ...

Best practices for managing a Media Stream in Node.js

One of the latest and most exciting features in modern browsers is HTMLMediaElement.captureStream(), which has recently been released in Chrome. Having grasped how it functions on the client side - allowing you to redirect the stream to other HTMLMediaEle ...

Python-JavaScript Integration Problem

I'm a beginner when it comes to Javascript, Python, and PHP. In my Javascript program, I have a button that triggers a Python script and displays the returned value on the screen. My goal is to steer clear of using Jquery and Json. Here are the snipp ...

Trouble with Adding and Showing Arrays

function resetValues() { var p = parseFloat($("#IA").val()); var q = parseFloat($("#IB").val()); var m = parseFloat($("#CGCD").val()); var aR = []; aR.push("GCD(" + p + "," + q + ")=" + m); document.getElementById("PGCD").innerHTM ...

Exploring the depths of npm in the realm of frontend development

Currently, I am delving into the realm of Javascript/Node development through self-teaching. While I grasp the concept of npm handling package installations for my Node application on the server side, I am struggling to comprehend how npm assists me with ...

conflict between ng-content and textarea elements

My custom component called my-textarea has a unique template structure: <textarea> <ng-content></ng-content> </textarea> However, when I try to input text into the component using the same method as a regular textarea HTML eleme ...

Clone all documents from a NodeJS mongoose collection and transfer them to a different server's database

I need assistance with migrating my database to a new server. My collection consists of approximately 410,000 documents, and I am looking to transfer them in batches of 100 to my new server that runs on mongodb. Below is the code I have written for this ...

Unveiling and Shifting Among Concealed HTML Forms

After going through numerous tickets with similar questions, I still can't seem to achieve what I want. So, I have no choice but to ask this question myself. I currently have an HTML page with 2 forms and 2 buttons. Both forms are initially hidden us ...

The function FileReader() is not functioning properly within a Vue computed property

I'm attempting to display a set of image thumbnails by dragging images onto the screen. Here is an example of my data structure: data() { return { files: [Image1, Image2, Image3] } } ...where each Image is in a blob format. Below is my co ...

Creating a data structure using jQuery/JavaScript when submitting a form - a guide

Currently, I am attempting to gather form input values and organize them into an array of objects that will then be sent to MongoDB. However, I am facing difficulty in figuring out how to include an array within the objects (refer to the comment in the cod ...

Troubleshooting broken links on a multi-page website built with node.js and ejs

I am encountering some difficulties with my multi-page website created in node.js/ejs. I suspect that the issue lies within the routing mechanism, although I have double-checked my routes and they seem to be configured correctly. The problem arises when I ...

Data is not found in req.body when making a fetch request

I have been attempting to send a fetch request to my server, but I am consistently receiving an empty req.body. Here is the client-side script: const form = document.getElementById('form1') form.addEventListener('submit', (e) => ...

Maximizing Efficiency: Using a Single Prototype-Instance Across Multiple HTML Pages

I have defined some Javascript "Classes" in separate files using the Prototype function as shown below: function Playlist(id, name){ this.id = id; this.name = name; } Playlist.prototype.getid = function(){return this.id;} Playlist.prototype.getn ...

What could be causing the Timeout error to occur in my Jasmine unit test for the HTTP interceptor?

I've been facing challenges with unit testing my interceptor since yesterday afternoon. Despite following multiple tutorials and Stack Overflow answers, I have managed to write what seems like the best code so far. However, I'm encountering an er ...

Difficulty Intercepting Browser's Back Button Press on Next.js Success Page

Currently, I am developing a Next.js application that includes a success page for users who have completed a payment transaction. My goal is to prevent users from navigating back to the payment page by intercepting the back button press and redirecting the ...

Utilize dynamically generated form fields to upload multiple files at once

Currently, as I delve into learning the MEAN stack, I am encountering difficulties with file uploads. Specifically, within a company form: this.companyForm = this.fb.group({ trucks: this.fb.array([]), ... }); The 'trucks' field i ...

Determine the generic types of callback in TypeScript based on the argument provided

There are numerous Stack Overflow questions that share a similar title, but it seems none of them address this particular inquiry. I'm in the process of developing a wrapper for an express RequestHandler that can catch errors in asynchronous handlers ...

The Ray Intersect function in THREE.js encounters issues when a div element is introduced

I have encountered an issue with my Three.js script. It works perfectly fine when there is only one target div on the page holding renderer.domElement. However, when I add another div with fixed height and width above the target div, the ray.intersectObjec ...

Searching for images in the filesystem using a recursive deferred approach

I've been attempting to iterate through the Android file system in search of any images. I created the following recursive method, but it's not functioning as expected. I've been struggling to determine a condition that can identify the end ...