I have the following Angular2 'pseudo' code and I want to keep the user class as simple as possible:
// ###### LIB CLASSES ######
@Component()
export abstract class Parent {
abstract childProvidedFactory;
factory_config;
ngOnInit() {
this.dataSource = new FactoryUser(this.childProvidedFactory, this.factory_config);
}
// this.dataSource initialized and may be used further
}
export class FactoryUser {
constructor (childProvidedFactory, factory_config) {
}
// ...
}
// ###### USER CLASS ######
@Component()
export class Child extends Parent {
@Input() config;
childProvidedFactory = () => {
// implementation
}
ngOnInit() {
this.factory_config = fnc(this.config);
super.ngOnInit();
}
}
I want the user who writes Child
not to need to call super.ngOnInit()
. So the idea is to move Parent
's ngOnInit
contents to the constructor. However at the constructor
execution time both the needed childProvidedFactory
and factory_config
are not yet available. Therefore I wrap the code with setTimeout
:
export abstract class Parent {
abstract childProvidedFactory;
factory_config;
constructor() {
setTimeout(() => {
this.dataSource = new FactoryUser(this.childProvidedFactory, this.factory_config);
}, 0)
}
// this.dataSource initialized and may be used further
}
Now I may remove super.ngOnInit()
from the Child
class.
On Chromium, when instrumented with console.log
s I get:
Inside child's ngOnInit()
Inside child's ngAfterViewInit()
Inside parent's setTimeout() within constructor()
Is it ensured that setTimeout
within Parent
's constructor will execute after Child
's ngOnInit
repectively after Child
's ngAfterViewInit
lifecycle hooks? If so could you explain why, i.e. how are the lifecycle hooks "scheduled" in the event loop in relation to setTimeout?
The code will be run with the major web engines only (WebKit, Blink, Gecko) and Angular >= 17.
Do you see any other potential issues?
The point is to avoid call of super.ngOnInit() in the Child. So there were other potential solutions:
In this solution I don't like the Child would need to use special name instead of ngOnInit.
The closest to my question is this, however there the constructor is not added to the mix.
I considered using one-time-initialization with afterNextRender() being called in the constructor. It technically works, however runtime error appears Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError
as the variable being initialized in the callback fn is used in the Childs template. So instead of undefined
it actually gains a value. With this option there'd be need to inject ChangeDetectorRef
to the abstract class' constructor, so the Child
would actually need to pass it to that constructor if I'm not mistaken. This would again unnecessarily complicate the Child
's code.
The method you are trying is really unreliable and will cause timing issue that are difficult to debug.
To handle the problem, you can use a decorator, which will call the parent ngOnInit
which must be a different name, since we cannot access super inside the constructor.
export function CallParentHook() {
return function (constructor: any) {
const original = constructor.prototype.ngOnInit;
constructor.prototype.ngOnInit = function () {
this.parentNgOnInit();
if (original && typeof original === 'function') {
original.apply(this, arguments);
}
};
};
}
@Component({
selector: 'app-child',
standalone: true,
imports: [JsonPipe],
template: `{{ dataSource | json }}`,
})
@CallParentHook()
export class Child extends Parent {
@Input() override config: any;
childProvidedFactory = () => {};
ngOnInit() {
console.log(this.dataSource);
}
}
import { JsonPipe } from '@angular/common';
import { Component, Directive, Input } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
export const fnc = (data: any) => data;
export class FactoryUser {
config: any;
constructor(childProvidedFactory: any, factory_config: any) {
this.config = factory_config;
}
// ...
}
export function CallParentHook() {
return function (constructor: any) {
const original = constructor.prototype.ngOnInit;
constructor.prototype.ngOnInit = function () {
this.parentNgOnInit();
if (original && typeof original === 'function') {
original.apply(this, arguments);
}
};
};
}
@Directive()
export abstract class Parent {
@Input() config: any;
abstract childProvidedFactory: any;
dataSource: any;
parentNgOnInit() {
this.dataSource = new FactoryUser(this.childProvidedFactory, this.config);
}
}
@Component({
selector: 'app-child',
standalone: true,
imports: [JsonPipe],
template: `{{ dataSource | json }}`,
})
@CallParentHook()
export class Child extends Parent {
@Input() override config: any;
childProvidedFactory = () => {};
ngOnInit() {
console.log(this.dataSource);
}
}
@Component({
selector: 'app-root',
imports: [Child],
standalone: true,
template: `
<app-child [config]="config"/>
asd
`,
})
export class App {
config = { name: 'Angular' };
}
bootstrapApplication(App);