'Angular 13 component loaded in iframe and ViewEncapsulation limitation
My component, DiscoveryComponent, is dynamically loaded into an iframe hosted by my AppComponent but oddly, the font-family set in the component's SCSS file is not applied.
Below is how I load DiscoveryComponent into AppComponent's iframe. I explicitly import Bootstrap's SCSS in DiscoveryComponent's SCSS file and set the $font-family-base variable before loading Bootstrap.
app.component.html
<iframe style="height: 500px; width: 100%;" #iframe></iframe>
app.component.ts
import { AfterViewInit, Component, ViewChild, ViewContainerRef, ElementRef } from '@angular/core'
import { DiscoveryComponent } from './discovery/discovery.component'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
encapsulation: ViewEncapsulation.ShadowDom
})
export class AppComponent implements AfterViewInit {
@ViewChild('iframe', {static: false}) iframe!: ElementRef
doc: any
public onLoad() {
const iframe = <HTMLIFrameElement> this.iframe.nativeElement
this.doc = iframe.contentDocument || iframe.contentWindow
this.createComponent()
}
private createComponent() {
const component = this.viewContainerRef.createComponent(DiscoveryComponent)
component.location.nativeElement.id = 'discovery'
this.doc.body.appendChild(component.location.nativeElement)
}
constructor(private viewContainerRef: ViewContainerRef) {}
ngAfterViewInit(): void {
this.onLoad()
}
}
discovery.component.html
<div class="container-fluid">
<div class="row">
<div class="col-6">I display using the Times font</div>
<div class="col-6">So do I</div>
</div
</div>
discovery.component.scss
$font-family-base: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
@import "bootstrap/scss/bootstrap";
discovery.component.ts
import { Component } from '@angular/core'
@Component({
selector: 'app-discovery',
templateUrl: './discovery.component.html',
styleUrls: ['./discovery.component.scss']
})
export class DiscoveryComponent {
constructor() {}
}
Any thoughts as to why Bootstrap styles are loaded but the $font-family-base is not being applied?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
