Search code examples
angulartypescriptangular7

Force child to call parent method


I have this situation:

abstract class A implements OnInit {
    ngOnInit() {
        this.abstractMethod();
    }

    abstract abstractMethod();
}

class B extends A implements OnInit {
    ngOnInit() {
        doOtherStuff();
    }
      
    abstractMethod() {
        doStuff();
    }
}

My problem is that B is not forced to call super.ngOnInit() inside it's ngOnInit method so abstractMethod is not called. Is there a way to force B to call super.ngOnInit()?

I'm asking this because I'm trying to create a base component for standard actions but some child components needs to do other things in ngOnInit (plus call abstractMethod()) and I'm trying to avoid mistakes caused by forgetfulness.


Solution

  • I had same problem. you can use this approach:

    abstract class A implements OnInit {
        ngOnInit() {
            this.abstractMethod();
            this.childOnInit();
        }
    
        abstract abstractMethod();
        abstract childOnInit();
    }
    
    class B extends A {
        childOnInit() {
            doOtherStuff();
        }
          
        abstractMethod() {
            doStuff();
        }
    }