How to hide angular app header and footer when displaying via iframe on another website
September 9th, 2024
To hide the header and footer of your Angular app when it’s displayed inside an iframe on another website, you can detect if the app is being loaded inside an iframe and conditionally hide those components.
Here’s a step-by-step approach to achieve this:
1. Detect if the App is Inside an iframe
You can check whether the app is being displayed inside an iframe by using the window.self !== window.top condition, which detects if the current window is different from the top-level window.
2. Hide the Header and Footer Conditionally
You can use Angular’s ngIf directive to conditionally render the header and footer components based on whether the app is inside an iframe.
Example Code
app.component.ts (Main component)
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
isIframe = false;
ngOnInit(): void {
// Detect if the app is running inside an iframe
this.isIframe = window.self !== window.top;
}
}
app.component.html (Main template)
<!-- Header -->
<header *ngIf="!isIframe">
<!-- Your header content here -->
<app-header></app-header>
</header>
<!-- Main content -->
<router-outlet></router-outlet>
<!-- Footer -->
<footer *ngIf="!isIframe">
<app-footer></app-footer>
</footer>
3. Explanation
In the ngOnInit() lifecycle hook of the main component (AppComponent), we detect if the app is running inside an iframe by comparing window.self and window.top.
The isIframe flag is set to true if the app is in an iframe.
In the template (app.component.html), the *ngIf=”!isIframe” directive is used to conditionally render the header and footer only if the app is not running inside an iframe.
4. Styling Considerations
Ensure that the absence of the header and footer doesn’t affect the layout of your app. You might need to adjust your CSS to handle the layout properly when those components are hidden.
This approach ensures that the header and footer will not appear when the Angular app is embedded inside an iframe on another website.