I'm working on an Angular 2 application that will be delivered via an iframe on other websites. Whilst testing I've noticed that when I load the application the App Component ngOnInit()
function is being called twice.
I'm finding this weird because when I'm testing the application 'on it's own', i.e. not though an iframe the App Component ngOnInit()
is only called once.
According to this answer this could happen due errors in child components. But in my case I'm not having the problem when running the application 'normally'.
Example Code:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
template: `<h1>My App!</h1>`
})
export class AppComponent implements OnInit {
constructor() {
console.log('App Component constructor()');
}
ngOnInit() {
console.log('App Component ngOnInit()');
}
}
Iframe Test:
<!DOCTYPE html>
<html>
<body>
<h1>My Test Page</h1>
<!-- iframe accessing my-app component -->
<iframe id="test-iframe" src="/#/" width="100%" height="1300px"></iframe>
</body>
</html>
I've tested the application with only an AppComponent
to be sure that no child components are causing any issues.
Console Output:
From my understanding, most likely the problem is, since the
ngOnInit()
method is called after the the@Component
finishes loading, the iframe element's loading begins right after thengOnInit()
life cycle finishes causing the iframesrc
value to be null.That means since the iframe is loading its self after the
ngOnInit()
is called, anysrc
value coming from the components would be foreign to it, hencenull
.Note: Iframe is like an outside browser injected in to DOM, so it has its own loading time.
So I would suggest using the
constructor(){}
for this kinds of things since its always called when the class is instantiated.