使用Angular 2 +

时间:2017-12-13 11:23:54

标签: css angular

我想动态加载我的html代码和css代码代码。加载html代码工作正常,但我不知道如何动态地注入CSS。

因此我写了以下组件:

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));
  }}

HTML.txt的内容是

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

我的CSS.txt的内容是

input {background:red}

1 个答案:

答案 0 :(得分:1)

您可以随时拥有文件路径并注入DOM

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

应从服务器

返回文件的路径