What could be causing Highlight.js to fail to work following a redirect?

After developing a small application to address a specific issue, I encountered a problem while attempting to apply code highlighting using highlight.js. The issue arises when navigating from site1 to site2 or vice versa - the highlight does not take effect. However, if I refresh the page on either site, the highlighting works perfectly.

The reason I need to use navigation is to retain the values of variables without losing them.

testr.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import hljs from 'highlight.js';

@Component({
  selector: 'app-testr',
  templateUrl: './testr.component.html',
  styleUrls: ['./testr.component.css']
})
export class TestrComponent implements OnInit {

  constructor(
    private router: Router
    ) {}

  ngOnInit() {
    hljs.initHighlightingOnLoad();
  }

  clickme(){
    this.router.navigate(['/teste']);
  }

}

testr.html

<p>testr works!</p>
<pre><code>var char; alert(1+1)</code></pre>
<button (click)="clickme()" value="Link">Link</button>

teste.ts

import { Component, OnInit } from '@angular/core';
import hljs from 'highlight.js';
import { Router } from '@angular/router';

@Component({
  selector: 'app-teste',
  templateUrl: './teste.component.html',
  styleUrls: ['./teste.component.css']
})
export class TesteComponent implements OnInit {

  constructor(
    private router: Router
  ) { }

  ngOnInit() {
    hljs.initHighlighting();
  }

  clickme(){
    this.router.navigate(['/testr']);
  }
}

teste.html

<p>teste works!</p>
<pre><code>var char; alert(1+1)</code></pre>
<button (click)="clickme()" value="Link">Link</button>

Answer №1

Highlight.js may encounter difficulty highlighting code that is not present when the page's "onload" event triggers. It seems likely that only the initial view of your first page exists upon loading, with the second view coming into existence in the DOM as you navigate to it.

If you switch pages, you will have to manually invoke initHighlighting in order to highlight any newly added code blocks on the page.

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

Updating the alignment between two input mat-select in Angular materialAlternatively:Fine-tuning the reference between

I am currently working on an Angular 6 app: I have two mat-select inputs that I want to connect in a way that if the selected option in my First select is equal to the value 'AAA', then the Second select should be hidden. First Mat-Select -> ...

Return to the previous page with different query parameters, not the same one

When it comes to reverting state location back by 1 step in Angular, we can utilize something along the lines of this.location.back();. This method works well unless the system redirects to the same URL but with different query parameters. In such cases, ...

Evaluate the Worth of a Property Established in a Subscription

Currently, I am using Jasmine for testing an Angular application and facing a challenge in testing the value of a property that is set within the subscribe call on an Observable within the component. To illustrate this point, I have created an example comp ...

Transferring data from a child to a parent component in Angular 2 using a combination of reactive and template-driven approaches

Recently delving into Angular 2 ( and Angular overall ) , I found myself at a crossroads with my co-worker. He opted for the template-driven method while I leaned towards the reactive-driven approach. We both built components, with his being a search produ ...

Neglectful TypeScript null checks overlooking array.length verification

When TypeScript is compiled with strict null checks, the code snippet below does not pass type checking even though it appears to be correct: const arr: number[] = [1, 2, 3] const f = (n: number) => { } while (arr.length) { f(arr.pop()) } The comp ...

tips for accessing the useState value once it has been initialized

When using the state hook in my code, I have: const [features, setFeatures] = useState([]) const [medicalProblem, setMedicalProblem] = useState([]) The medicalProblem variable will be initially populated with a response from an API call: useEf ...

What could be causing the issue: Unable to locate or read the file: ./styles-variables?

I'm currently following a tutorial on how to create responsive layouts with Bootstrap 4 and Angular 6. You can find the tutorial here. I've reached a point where I need to import styles-variables.scss in my styles file, but I keep encountering t ...

Having trouble getting my Angular 2 project up and running

After downloading a MEAN stack project from bitbucket, I attempted to run the front end (Angular 2) locally by navigating to the angular folder and using the command ng serve. However, I encountered the following error: "The serve command requires to be ...

The unknown number of arguments in a Typescript generic type

I'm currently working on developing a function that utilizes a generic type to take in a function, an array of arguments for the function, and then apply them accordingly. However, I am facing an issue with TypeScript not correctly interpreting the ar ...

What is the best way to attach a button to a mat-drawer?

I am facing an issue with aligning a button to a mat drawer located to the right of the screen to ensure a clear overall design. Check out this example How can I achieve this alignment? My current approach involves placing the button inside the drawer an ...

Deactivating a Component in Ionic Angular

I am interested in including a CanDeactivate Guard in my Ionic Angular project. After reading about the new "CanDeactivateFn" Guard, I have been unable to find any information or examples on how to implement it. Could someone provide me with an example? ...

Exploring the Potential of Using ngIf-else Expressions in Angular 2

Here is a code snippet that I wrote: <tr *ngFor="let sample of data; let i = index" [attr.data-index]="i"> <ng-container *ngIf="sample.configuration_type == 1; then thenBlock; else elseBlock"></ng-container> <ng-template #t ...

Creating a module within a component in angular - step by step guide

I am interested in dynamically creating a component inside another component. This will allow me to pass my dynamic HTML template directly to the decorator like this: //code /** * @param template is the HTML template * @param container is @ViewChild(& ...

What is the best way to include bootstrap using webpack?

I am currently building a webapp using Typescript and webpack. I have been able to successfully import some modules by including them in my webpack.config.js file as shown below. However, no matter how many times I attempt it, I cannot seem to import the b ...

Error in JSON format detected by Cloudinary in the live environment

For my upcoming project in Next.js, I have integrated a Cloudinary function to handle file uploads. Here is the code snippet: import { v2 as cloudinary, UploadApiResponse } from 'cloudinary' import dotenv from 'dotenv' dotenv.config() ...

What could be causing my Angular 7 header to be unresponsive?

I am facing issues with my http, header, and RequestOption in the API. I am working with Angular 7.1 and have tried various methods to resolve the problem without success. The error message I am receiving is: The token is not being passed in the header ...

The 'filter' property is not found on the type '{}'

I'm currently attempting to implement a custom filter for an autocomplete input text following the Angular Material guide. https://material.angular.io/components/autocomplete/overview Here's what I have so far: TS import { Component, OnInit } ...

Is it possible to customize a directive to define the placeholder text for an input field with Angular Material?

Here is some sample HTML code: <md-input-container> <input mdInput myCustomDirective formControlName="email" > </md-input-container> My goal is to set the placeholder in my custom directive. I attempted to do this usi ...

Dealing with the "net::ERR_CERT_DATE_INVALID" issue within Ionic 4

When sending an "http" request in Ionic4, the response neither falls under the success callback nor gets handled by the error handling block. It just keeps loading indefinitely. I need a solution to properly handle this error in Ionic4 (Client side). I at ...

Encountered an error while attempting to run the org.apache.maven.plugins:maven-jar-plugin:2.6:jar goal

Currently, I'm engaged in a comprehensive project that involves both backend and frontend development. The frontend aspect (built on the angular2 framework) is functioning smoothly with commands like 'npm start' and 'ng build'. How ...