The issue with Angular 2's Parameterised router link component not fully refreshing

I'm trying to figure out how to show a set of images when I click on a specific menu item. The menu structure looks like this:

<ul id="demo23" class="collapse">
    <li>
        <a [routerLink]="['image-gallery','Picasso']">Picasso</a>
    </li>
    <li>
        <a [routerLink]="['image-gallery','Vincent']">Vincent</a>
    </li>
    <li>
        <a [routerLink]="['image-gallery','Rembrandt']">Rembrandt</a>
    </li>
</ul>

The code for the router component is as follows:

export class ImageGalleryComponent {

private artistName: String;
private galleryRoute: ActivatedRoute;
private apiService: ApiService;
private imageList;
private sanitizer: DomSanitizer;

constructor(route: ActivatedRoute, apiService: ApiService, sanitizer: DomSanitizer) {
    this.galleryRoute = route;
    this.apiService = apiService;
    this.imageList = new Array;
    this.sanitizer = sanitizer;
}

ngOnInit() {
        this.galleryRoute.params.subscribe(params => {
        console.log("Initial image list length");
        console.log(this.imageList.length);


        this.artistName = params['artistName'];

        let artistName2Send = this.artistName;

        console.log(this.artistName);
        this.apiService.sendAsNonJSON("http://localhost:8080/icreate/getImages", artistName2Send).subscribe(demo => {
            let imageList: String[] = demo;


            var imageListLength = imageList.length;
            var index;
            for (index = 0; index < imageListLength; index++) {
                this.imageList[index] = this.sanitizer.bypassSecurityTrustHtml(imageList[index] as string);
            }

            console.log(this.imageList);


        });
    });

The app.routing.ts entry for this functionality is:

{ path: 'image-gallery/:artistName', component: ImageGalleryComponent }

When clicking the first menu option, it correctly displays 4 images. However, when clicking on the second menu option, instead of displaying just 1 image, it shows 4 images – the correct one and the previous 3 from the previous selection. How can I ensure that only the newly selected images are displayed and remove any previously shown images? Any suggestions would be appreciated.

Answer №1

A little while back, I encountered a similar issue that stemmed from Angular's component reuse causing URL changes without refreshing the component. After much searching on Stack Overflow, here is how I managed to solve it. You have to subscribe to parameter changes and take action within the subscription.

1) Start by importing ActivatedRoute from @angular/route and Subscription from rxjs

    import { Subscription } from 'rxjs/Rx';
    import { ActivatedRoute} from '@angular/router';

    export class YourComponent implements onInit, onDestroy {
    private subscription: Subscription;

2) Within your ngOnInit function, subscribe to parameter changes and implement necessary actions

    ngOnInit() {
     this.subscription = this.activatedRoute.params.subscribe((params) => {
        this.productId = params['id'];
        // Add logic here to trigger the necessary changes
        this.product = this.productService.getProduct(this.productId);
        console.log(this.product);
    });  

}

3) Lastly, remember to unsubscribe in ngOnDestroy function

    ngOnDestroy() {
    this.subscription.unsubscribe();
}

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

Error Checking in AngularJS Form Submission

According to my form.json file, I have a form that needs validation and a simulated submission. Firstly, I need to address this issue: fnPtr is not a function Next, I want to submit the form to a mocked API endpoint that will return true or false. Can I ...

Having Trouble with Updating Variables in AngularJS Service

I am faced with a challenge involving a series of images displayed side by side. My goal is to determine which image has been clicked, retrieve the relevant information, and display it in a modal window. HTML Markup <section class="portfolio-grid ...

jqGrid: Enhance the advanced search dialog by updating the column dropdown feature following the addition of a column using the column

I am encountering an issue with the advanced search feature of the jqGrid. It appears that the advanced search dialog box is only generated once, when the searchGrid function is called. After I have opened the advanced search dialog once and then add a co ...

Custom Validation requires promises to be present

Creating a custom validation method to validate ranges can be done in different ways. Below is an example of how to achieve this: static ratingRange=(min:number,max:number) => { return (control:AbstractControl):Promise<ValidationErrors|null&g ...

Base URL for making Http Requests in an Angular application

I am currently working on an angular application that is hosted on a test server running IIS with a .net core backend. The application is set up on a virtual directory, for example www.myTestApp/crm (the actual domain name being fictional). During the buil ...

Issue with JQuery addClass functionality in Firefox

I've come across numerous posts on this topic, but none of them have provided a solution. I recently added drag and drop functionality to my website. When I drag an item over a valid container, I add a specific class to it. Here is the HTML for the ...

How to set cells to plain text in google sheets

I've been grappling with a formatting issue that I'm hoping someone can assist me with. In my script, there's a point where I need to combine the date value (e.g., 11/20/2020) from one column with the time (3:00 PM) from another column. This ...

Ways to show a child's component element within the parent container

Within my Angular 11 project, there exists a component that exhibits a child component containing assorted table filters: Parent Component <table-filters></table-filters> <table> ... </table> Child Component (table-filters) <f ...

Create a Bootstrap modal that includes a checkbox option to prevent it from appearing again in

I am attempting to display a bootstrap modal upon body load based on a value retrieved from a MySQL database. The bootstrap modal is included in the body and shown successfully depending on the database value using the following code snippet: $results ...

jQuery 'if' condition not getting detected

My jQuery code is not recognizing an if statement. You can check out the CodePen link here. On my site, I have 4 page transitions - page right, page left, page up, and page down. The contact page is hidden beneath the main hero sections and appears with t ...

Why are my Chrome Div regions failing to expand to their full width?

I have been searching but couldn't find an answer to my issue, so I apologize if this question has been asked before. I am working on a simple site layout and noticed that two of the div regions do not expand fully in Chrome, however, they do in Firef ...

issue with accessing the code through the web browser

Currently, I am developing a web application using ASP.NET MVC5. I have been coding and pushing my work to GitHub. However, I recently encountered an issue where I can no longer view my application on the browser. The "View in browser" option has disappear ...

Angular Material Toolbar Experiencing Color Distortion

To see the issue in action, check out this CodePen: An ongoing problem I've encountered with Angular Material involves distorted colors on the toolbar. The edges of the toolbar display one shade of green, while the middle shows a different shade. Tak ...

What is the best way to create space between floated elements and a cleared element?

I have a webpage with various floated boxes and a footer positioned at the bottom. The issue arises when trying to create space between the boxes and the footer without using margins. #main { max-width: 700px; margin: 0 auto; } .box { width: 46.6 ...

``There seems to be an issue with the functionality of Angular's $routeProvider

I'm currently facing an issue with my setup. I have a local angular front-end running on localhost using an Apache Server on Linux. When I try to access localhost, everything works fine and I can see my index.html. However, I have a link in the index. ...

Is it possible for image.src to pose a security threat?

Here is the code snippet I am working with: var image = new Image(); image.src = "https://MyTrackingSite.com/?myTrackingParameter=whatever" I noticed that the image is not added to the DOM tree. Is it still rendered by the command "image.src"? Could this ...

Show angular variable data in a table based on their index

I have an array of angular variables with values like [ 170, 1, 130, 3, 134, 4.... and so on]. I would like to present these values in a table format where the even positioned values are shown in one column and the odd positioned values in another column. ...

Remove an element from an array based on the index provided by the front end

Currently, I am attempting to eliminate a specific item from a PHP array stored in a JSON file. Here is an example of the JSON file structure: { "1.49514754373E+12": { "description": "I don't like it", "fileNames": [ " ...

What is the process of displaying events from components within ng2 submodules?

My dilemma involves two components with straightforward output events and handlers. I am attempting to pass a value from a child submodule to a component within my app.module. Here is the snippet of code from my app.component.ts: @Component({ selector: ...

Unable to retrieve user attributes (provided as res.locals.user) in express and hbs view

Here is a snippet of code I use to verify user tokens and store the user information in req.locals: exports.isLoggedIn = async (req, res, next) => { if (req.cookies.jwt) { try { const decoded = await promisify(jwt.verify)( ...