I want to add code to child's ngOnInit method from a parent class. Can I somehow do something similar to this?
export class Child extends Parent {
constructor(){
super(this.ngOnInit);
}
ngOnInit(){
console.log('Child onInit');
}
}
And Parent:
export class Parent {
constructor(childOnInitMethod: any){}
ngOnInit(){
console.log('Parent added code to child onInit');
this.childOnInitMethod.apply(this, arguments)
}
}
The problem is that on the child constructor I do not have "this" available.
UPDATE: Find here the current code
For now, this is what I've done. Child class extends parent's ngOnInit and ngOnDestroy. What I want to achieve is to avoid calling parent "super.subscribeEvents();" like this:
ngOnInit() {
window.onresize = () => console.log('resizing');
super.subscribeEvents();
}
What I want to do is to add code to the Child's ngOnInit from Parent. These are the classes:
export class DatatablePage extends EventSubscriber {
@Output() onLoadRow: EventEmitter<any> = new EventEmitter();
public gridApi: GridApi;
constructor(
events: Events
) {
super(events, [
{ eventName: 'datatable:updateList', callbackFunction: () => this.onLoadRow.emit() },
{ eventName: 'datatable:resizeTable', callbackFunction: () => this.gridApi.sizeColumnsToFit() }
])
}
ngOnInit() {
window.onresize = () => console.log('resizing');
super.subscribeEvents();
}
}
And Parent:
export class EventSubscriber {
constructor(
private events: Events,
public eventSubscriptions: EventObject[]
) {
}
ngOnInit() {
this.subscribeEvents();
}
ngOnDestroy() {
this.unsubscribeEvents();
}
subscribeEvents() {
this.eventSubscriptions.forEach((eventSubscription: EventObject) => {
this.events.subscribe((eventSubscription.eventName), eventSubscription.callbackFunction)
});
}
unsubscribeEvents() {
this.eventSubscriptions.forEach((eventSubscription: EventObject) => {
this.events.unsubscribe((eventSubscription.eventName), eventSubscription.callbackFunction)
});
}
}
the below solution should work.
class Parent {
constructor(){}
ngOnInit(){
console.log('Parent added code to child onInit');
this.ngOnInit()
}
}
class Child extends Parent {
ngOnInit() {
console.log('Child onInit');
}
invokeSuperOnInit() {
super.ngOnInit();
}
}
const a = new Child();
a.invokeSuperOnInit();
Execution:
Created object of Child Class and assigned to a.
calling invokeSuperOnInit Method on the object a.
ngOnInit of the Parent is invoked.
In the parent NgOninit We are calling ngOnInit of the Child. The Child ngOnInit is invoked because "this" will always stay same through out the hierarchy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With