Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
How to Insert style tag dynamically in html in angular

How to Insert Style Tag Dynamically in Angular ?

Aman Jain, August 4, 2022March 16, 2024

Sometimes we want to insert style tag in angular app, For an instance we have third party APIs or widget and we wanted to add it in our page then in this condition provided script and style are not angular friendly or we can say it can be pure JavaScript or Style. so to insert this type of style we need to load it dynamically in our Dom.

In angular we can add those style in two ways first one is using the pure javascript way and other in angular way which also work on server application.

Let’s discuss the both way to Insert style tag dynamically in html in angular

Load style tag url using pure javascript in component

In this way we will create a component and then load the style in Dom so it can work as expected as below

loadScriptByUrl(url, afterload) {
    let dynamicScript = document.createElement('style');
    dynamicScript.type = 'text/css';
    dynamicScript.async = true;
    dynamicScript.src = url;
    dynamicScript.id = 'dynamic_' + this.count;
    document.body.appendChild(dynamicScript);
    this.count++;

    dynamicScript.addEventListener('load', () => {
      afterload(dynamicScript, dynamicScript.id);
    });
  }

Load style tag text using pure javascript in component

In this way we will create a component and then load the script in Dom so it can work as expected as below

loadScriptByUrl() {
  let dynamicScript = document.createElement("style");
  dynamicScript.type = "text/css";
  dynamicScript.async = true;
  dynamicScript.text = "body{color:red}";
  document.body.appendChild(dynamicScript);
}

Understand it with an example

Step 1 : Create an angular app

First step is to setup an angular app using below command

ng new example-component

Step 2: Create a Component

Create a component so we can use insert the style tag in it dynamically.

ng g c test-style
import { Component, OnInit, Input } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

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

  ngOnInit() {

  }

}

Step 3 : Add loadStyleUrl method to component

Now add the logic for adding style tag in component in JavaScript way

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-test-style',
  templateUrl: './test-style.component.html',
  styleUrls: ['./test-style.component.css'],
})
export class TestStyleComponent implements OnInit {
  count = 0;
  constructor() {}

  ngOnInit() {
    
    this.loadStyletByUrl(
      'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/themes/base/jquery-ui.min.css',
      function (scriptref, id) {
        
        // do your work after load
      }
    );
  }

  loadStyletByUrl(url, afterload) {
    let dynamicScript = document.createElement('style');
    dynamicScript.type = 'text/css';
    dynamicScript.async = true;
    dynamicScript.src = url;
    dynamicScript.id = 'dynamic_' + this.count;
    document.body.appendChild(dynamicScript);
    this.count++;

    dynamicScript.addEventListener('load', () => {
      afterload(dynamicScript, dynamicScript.id);
    });
  }
 
}

Or in Angular server side rendering

import { DOCUMENT } from '@angular/common';
import { Component, Inject, OnInit, Renderer2 } from '@angular/core';

@Component({
  selector: 'app-test-style',
  templateUrl: './test-style.component.html',
  styleUrls: ['./test-style.component.css'],
})
export class TestStyleComponent implements OnInit {
  count = 0;
  constructor(
    private _renderer2: Renderer2,
    @Inject(DOCUMENT) private _document: Document
  ) {}

  ngOnInit() {
    
    this.loadStyleByAngularWay(
      'alert("Dynamic loaded SSR")',
      function (scriptref, id) {
       
        // do your work after load
      }
    );
  }

   
  public loadStyleByAngularWay(text,afterload) {
    let script = this._renderer2.createElement('style');
    script.type = `text/css`;
    script.text = text;

    this._renderer2.appendChild(this._document.body, script);
    script.addEventListener('load', () => {
      afterload(script);
    });
  }
}

Here we added both way using loadStyleByAngularWay and loadStyleByUrl method, also we added callback so we can only run the external style method after load.

we added a library to format input field https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/themes/base/jquery-ui.min.css

Step 4 : Add html in template

Add simple html in template so we can test our implementation

<p>
  test-style works!

  
</p>

Related

Javascript Angular angulardynamicscript

Post navigation

Previous post
Next post

Related Posts

Javascript Angular If Else

How to use NgIf, Ngif else and elseif in angular 12 ?

April 2, 2022November 7, 2023

In this tutorial we will learn to use angular if else, ngIf, ngif else and elseif. if else is used to make conditional statement in template same as we can also use if else. As we all programmers know if or if else condition is used to create conditional statements…

Read More

Show dropdown list from ajax response in jQuery

September 10, 2021September 10, 2021

Showing Dynamic Select Box using jQuery and Php,MySql In this tutorial, we are going to learn the dropdown list using AJAX. Loading dropdown values from AJAX requires knowledge of javascript, jQuery, php and html. Sometimes it requires to load the dropdown like countries, state, city list dependently. In this case…

Read More
Javascript Password and confirm password validation in angular

Password and confirm password validation in angular 14 ?

September 9, 2022March 16, 2024

Angular 14 provides built-in library for validation but it doesn’t have built in validation for password and confirm password. Angular 14 has release and we are excited to work with new feature so i am also updating the most search article with latest version of angular. so in this tutorial…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • August 2025
  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Transformative Power of Education in the Digital Age
  • Understanding High Vulnerabilities: A Closer Look at the Week of July 14, 2025
  • Exploring Fresh Resources for Web Designers and Developers
  • The Intersection of Security and Technology: Understanding Vulnerabilities
  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version