Recently, I've been trying out a new approach by embedding Bootstrap components in an iframe. However, despite loading the necessary stylesheet and scripts, the elements seem to be missing their styles. Can anyone shed some light on why this might be happening? You can view my code snippet here: https://stackblitz.com/edit/angular-ivy-2pga8q.
import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'app-canvas',
templateUrl: './canvas.component.html',
styleUrls: ['./canvas.component.scss'],
})
export class CanvasComponent implements AfterViewInit {
@ViewChild('canvas') canvas: ElementRef<HTMLFrameElement>;
ngAfterViewInit(): void {
this.generateWebsite();
}
generateWebsite(): void {
this.insertHeadElements();
this.insertBodyElements();
}
insertHeadElements() {
const canvas = this.canvas.nativeElement.contentWindow.document.head;
const bootstrapStyleElement = document.createElement('link');
bootstrapStyleElement.rel = 'stylesheet';
bootstrapStyleElement.href =
'https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"';
canvas.append(bootstrapStyleElement);
const jqueryScriptElement = document.createElement('script');
jqueryScriptElement.src = 'https://code.jquery.com/jquery-3.5.1.slim.min.js';
canvas.append(jqueryScriptElement);
}
insertBodyElements() {
this.insertNavbarElement();
}
insertNavbarElement() {
const canvas = this.canvas.nativeElement.contentWindow.document.body;
const navbarElement = document.createElement('nav');
navbarElement.className = 'navbar navbar-expand-lg navbar-light bg-light';
navbarElement.innerHTML =
'<a class="navbar-brand" href="#">Fixed navbar</a><button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button><div class="collapse navbar-collapse" id="navbarCollapse"><ul class="navbar-nav mr-auto"><li class="nav-item active"><a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a></li><li class="nav-item"><a class="nav-link" href="#">Link</a></li><li class="nav-item"><a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a></li></ul></div>';
canvas.append(navbarElement);
}
}