I store different pages in html to be shown in an router-outlet in some angular-component.
The pages should have their own css-files and their own js-files for logic.
My content-handling-component looks like this:
import { Component, OnInit, Pipe, PipeTransform } from '@angular/core';
import { ContentService } from '../content.service';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-content-handler',
standalone: true,
templateUrl: './content-handler.component.html',
imports: [HttpClientModule],
styleUrls: ['./content-handler.component.scss'],
})
export class ContentHandlerComponent implements OnInit {
topic: string = '';
subtopic: string = '';
currentContent: SafeHtml = 'test';
currentSubject: string = 'planeGeo';
private routeSubscription: Subscription | undefined;
constructor(
private contentService: ContentService,
private sanitizer: DomSanitizer,
private route: ActivatedRoute,
private http: HttpClient
) {}
ngOnInit(): void {
this.routeSubscription = this.route.params.subscribe((params) => {
//console.log(params);
this.topic = params['topic'];
this.subtopic = params['subtopic'];
this.getCurrentContent();
});
}
ngonDestroy(): void {
if (this.routeSubscription) {
this.routeSubscription.unsubscribe();
}
}
getCurrentContent() {
const jsonPath = `assets/models/${this.currentSubject}.json`;
this.http.get<any>(jsonPath).subscribe((data) => {
const htmlPath =
data[this.currentSubject]['topics'][this.topic][this.subtopic][
'htmlCode'
];
if (htmlPath) {
this.http
.get(htmlPath, { responseType: 'text' })
.subscribe((htmlData) => {
this.currentContent =
this.sanitizer.bypassSecurityTrustHtml(htmlData);
});
} else {
console.error('HTML-Code nicht gefunden.');
}
});
}
}
The getCurrentContent()-method gets the path of the html-files from a json, where other data of the corresponding topic is stored, too. It then parses it through the sanitizier.
The corresponding html is just:
<div [innerHTML]="currentContent"></div>
When I load an html-file with linked css and js-files, they have no effect. I tried different things like creating my own @Pipe like explained HERE, but this didn't work. I also tried to put the css-rules in the global scss-file. That worked, but I dont' have a clue where to put certain js-functions in to make them global.
I think the problem is that the html is only read as a string and so the paths for css and js can't be interpreted right or the DOMSanitizier causes it.
Anyone knows a solution?