Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically load CSS from a String to your Component using Angular 2+

Tags:

css

angular

i want to load my html-code and css-code code dynamically. Loading the html code is working fine, but i have no idea how inject the CSS dynamically.

Therefore i wrote following Component :

import { Component, Input } from '@angular/core';
import { Injectable, Inject } from '@angular/core';
import { Http, URLSearchParams } from '@angular/http';
import { APP_BASE_HREF } from '@angular/common';
import { ORIGIN_URL } from '../../shared/constants/baseurl.constants';
import { HttpClient } from '@angular/common/http';
import { DynamicComponentData } from './dynamic-component.data';
import { Observable } from 'rxjs/Observable';
import { TransferHttp } from '../../../modules/transfer-http/transfer-http';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  template: `
  <div [innerHTML]="html"> </div>

  `
})
export class DynamicHTMLComponent implements DynamicComponentData {
  html: any;
  css: any;
  constructor(
    @Inject(DOCUMENT) private document,
    private http: HttpClient,
    private _sanitizer: DomSanitizer,
    private transferHttp: TransferHttp,
    @Inject(ORIGIN_URL) private baseUrl: string) {
    this.getHTML();
    this.getCSS();
  }

  @Input() data: any;

  getHTML() {
    this.http.get(`${this.baseUrl}/HTML.txt`, { responseType: 'text' })
      .subscribe(data => this.html = this._sanitizer.bypassSecurityTrustHtml(data));
  }

  getCSS() {
    this.http.get(`${this.baseUrl}/CSS.txt`, { responseType: 'text' })
      .subscribe(data => this.css = this._sanitizer.bypassSecurityTrustHtml(data));
  }}

The content of HTML.txt is

 <input id="name" name="name">

The content of my CSS.txt is

input {background:red}
like image 366
dindunuffin Avatar asked Nov 27 '25 12:11

dindunuffin


1 Answers

You can have the file path and inject into the DOM anytime

document.getElementByTagName('link').href="..............."

The path of the file shall be returned from the server

like image 156
Aravind Avatar answered Nov 30 '25 06:11

Aravind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!