Angular 8 router reloads the full page instead of partial loading. Why?

435 views Asked by At

I am developing a web application using Angular 8 where i need to created a dynamic menu from database. Before proceed to final work i did a little test where i got unexpected result. i set a variable in .ts file to hold the code for menu and then bind that variable at html file by [innerHTML]. when i click the link expect component is loading but the problem is instead of loading partially it make a full Page reload. I do not understand why partial rendering is not happening. Please help me in this regard..

main.component.ts

import { Component, OnInit } from '@angular/core';
import { MenuService } from 'services/menu.service';
import { MenuDTO } from 'dto/MenuDTO';

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styles: []
})
export class MainComponent implements OnInit {
  menuStr: string;
ngOnInit() {
   this.menuStr = '<a routerLink="Supplier" href="/main/Supplier" >Supplier</a>';
  }
}

main.component.html

<div [innerHTML]="menuStr | safehtml ">

  </div>
  <a routerLink="vhe" href="/main/vhe" >Vehicle List</a>

Here Safehtml is pipe which is as follows

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';


@Pipe({ name: 'safehtml' })
export class SafeHTMLPipe implements PipeTransform  {
  constructor(private sanitizer: DomSanitizer) { }


  public transform(value: any, type: string): any {

    return this.sanitizer.bypassSecurityTrustHtml(value);

  }
}

So here is two link 1. Supplier and 2. Vehicle List. Frist link is created by binding [innerHTML] option and second link direct at HTML Code. while click on first link component rendered with full page refresh and while click on second like component rendered Partially. My question is for first link why component rendered with full page refresh? Why component do not rendered partially while link created by binding [innerHTML] ?

1

There are 1 answers

2
Tony On

You dont have to specify href on anchor tag, here is the sample app

stackblitz

instead of sending html from server it will be better to send only the routes in JSON and loop through it for example :

ts
this.collection= [{"title":"Vehicle List",routerLink:"/main/vhe"},"title":"Supplier",routerLink:"/main/Supplier"}];

html
<a *ngFor="let item of collection"  [routerLink]="item.routerLink">{{item.title}}</a>