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

The formBuilder controls' setValue() and patchValue() methods are not functional when called within a method of a Cordova plugin

In developing my Ionic tabs app, I have integrated the cordova-plugin-datepicker and utilized Angular Material to design the form fields. One issue I encountered is setting the text input's value with the date obtained from the plugin’s calendar in ...

Tips for Angular4: ensuring ngOnDestroy completion before navigation

My task involves managing a list of objects where the user can choose an object to edit using a child component. However, when the user returns to the list component, the child component needs to clean up in the ngOnDestroy method, which includes making a ...

Leverage Async Await for Setting Response Data in TypeScript

Currently, I am making multiple API requests with different data and storing all the responses in an array. Then, I am using .map to map the response array to my original array to update the data. However, it seems like the process is not working correctly ...

Leverage the power of InfiniteSWR in your project by integrating it seamlessly with

If you're looking for a comprehensive example of how to integrate useSWR hooks with axios and typescript, check out the official repository here. import useSWR, { SWRConfiguration, SWRResponse } from 'swr' import axios, { AxiosRequestConfig, ...

Can the child component ensure that the Context value is not null?

In the process of developing a Next.js/React application with TypeScript, I've implemented a UserContext in pages/_app.js that supplies a user: User | null object to all child components. Additionally, there's a ProtectedRoute component designed ...

Guide to implementing an enum in an Angular Component

Having a global state (or "mode") in my Angular Components is leading me to look for more efficient ways to code. Here is what I have tried: @Component({ .... }) export class AbcComponent implements OnInit { enum State { init, view, edit, cre ...

Angular 2 NG Dynamic Grid Columns

Can a grid be created where column widths are not fixed in pixels? This would particularly come in handy when paired with sizeColumnsToFit(). Take, for instance, the scenario in which the ID and Name columns should adjust to content size while the Descrip ...

Encountering an Angular 12 error 401 upon refreshing the page

Currently, I am working on a login form using angular 12 with Spring Boot that includes basic authentication spring security. When a user successfully logs in, they are directed to the main page which offers CRUD actions as depicted in the images linked be ...

Unable to retrieve data using Http Get in Angular 2

In my service.ts class, I have the following method: getData(username:string, password:string) { let params: URLSearchParams = new URLSearchParams(); params.set('username', username); params.set('password', password); ...

The type 'undefined' cannot be assigned to type 'CartItem'

While running my program, I encountered the error 'Type 'undefined' is not assignable to type 'CartItem'. Unfortunately, I am unable to resolve this issue :(. import { Injectable } from '@angular/core'; import { CartItem ...

What causes the variation in Http Post Response between the Console and Network response tab?

Currently, I am tackling an issue in angular2 related to HTTP post response. The problem arises when my endpoint is expected to return a boolean value. Interestingly, the response appears correctly in Chrome's Network response tab; however, upon loggi ...

Request for /Account after Keycloak token request in Angular app

I have been working on an Angular and Keycloak project. I followed a tutorial that helped me integrate Keycloak into Angular, which can be found here: https://www.npmjs.com/package/keycloak-angular My public client is able to request a token, but when it ...

Show a dropdown menu based on a certain condition in Angular

Is there a way to conditionally display select options like this? <select id="updateType" class="form-control" formControlName="updateType"> <option value="personalDetails">Personal</option> <option value="addressD ...

I am encountering challenges with submitting the form

I am encountering an issue where I want to submit the form on button click and navigate to the next page, but instead I get an error message saying: "Form submission canceled because the form is not connected". Does anyone have a solution for this problem ...

Experience the magic of live streaming with our cutting-edge technology bundle featuring RTSP streaming, AspNet 5 API integration, FFM

Description: I am working on an API (ASP.Net 5) that connects to an IP Camera through RTSP. The camera sends a h264 stream converted with ffmpeg as an m3u8 stream, which is then returned to the Angular client in the following manner: public async Task< ...

What is the best method for installing the most recent 1.1.5 version of is-callable?

After running the command npm install, an error occurred: npm ERR! code ETARGET npm ERR! notarget No matching version found for is-callable@^1.1.5. npm ERR! notarget In most cases you or one of your dependencies are requesting npm ERR! notarget a ...

Is the transcluded content visible to the class as a whole?

Angular2 makes it simple to create a component like this: @Component({ selector: 'some', properties: ['header'] }) @View({ template: ` <div> <h2>{{ getFormattedHeader() }}</h2> <p><conte ...

How can you implement multiple validators on a single control in Angular 2?

I've been working on a form using Angular2 and I've implemented two custom validators for the email address field. The initial validator checks for valid email format, while the second (which is asynchronous) checks if the email address already ...

What is a suitable alternative to forkJoin for executing parallel requests that can still complete even if one of them fails?

Is there a more robust method than forkJoin to run multiple requests in parallel and handle failed subscriptions without cancelling the rest? I need a solution that allows all requests to complete even if one fails. Here's a scenario: const posts = th ...

Creating a Dynamic Clear Button for a Text Area in Angular

Working on my Angular application, I have implemented a form with a textarea element. My goal is to incorporate a clear button inside the textarea element that should: Appear only when the textarea is focused Disappear when the textarea is out of focus ( ...