I'm working on developing a reusable angular2 component that can take an array of URLs linking to HTML files on my server. The goal is to generate a content window with tabs for switching between different "chapters", effectively swapping out the HTML and CSS within the content window. I've experimented with various approaches, such as iframes (which didn't work), deprecated ng-include workarounds from Angular 1 found on StackOverflow, and even building a component that allows inputting HTML but struggles with applying styles properly due to Angular stripping out style and script tags. Here's what I've attempted:
Within my parent component class:
htmlInput: string = "<h1>Why Does Angular make this so hard?</h1>";
cssInput: string = "h1 { color:red; }"
Parent Component HTML:
<app-html [html]='htmlInput' [css]='cssInput'></app-html>
My HTML Component:
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-html',
template: '<div [innerHtml]=html></div>', //This works but no style
//template: '{{html}}', //This displays the actual markup on page
styles: ['{{css}}'] //This does nothing
//styles: ['h1 { color: red; }']//Also nothing
})
export class HtmlComponent implements OnInit {
@Input() html: string = "";
@Input() css: string = "";
ngOnInit() {
}
}
The code renders:
Why Does Angular make this so hard?
However, the red color isn't applied. It seems like the style might be processed before adding innerHtml to the DOM. Just using {{html}} displays the markup with visible h1 tags.
My aim is to easily flip through existing HTML pages stored on my server in a folder, all styled consistently and without reloading the entire page. Creating routes for each one would be cumbersome given the number of pages, and I prefer not to create individual routes for navigation. Any suggestions for embedding styled HTML dynamically with the latest version of Angular 2 (2.0.0-beta.17) are welcome. Alternatively, if there's a more Angular-friendly approach to achieve similar results, I'd appreciate hearing about it.
Thank you.
Edit:
To address my issue, I created a pipe to sanitize HTML before adding it to an iframe.
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {}
transform(url: string) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}
This enables passing HTML into the iframe:
<iframe width="100%" height="1000" frameBorder="0" [src]="url | safe"></iframe>
This solution proves useful for displaying old pages containing jQuery and specific styles. It serves as a quick workaround for showcasing them.