3

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}
1
  • Why not use ngStyle ? Commented Dec 13, 2017 at 11:28

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yes but in case the css file is not on the server. For example getting a String passed from Rest API ...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.