yu13
yu13

Reputation: 21

ngOnInit does not work due to build mode when using library

If I create a library with the following configuration, install it on the application side, and inherit and use it, If ng build --prod=true, ngOnInit will not be called. If ng build, ngOnInit is called.

It works if you quit the library and put the library source into the application. However, I want to make it a library because I want to use it in common.

export abstract class LibrarySampleBase implements OnInit {
    public ngOnInit() {
        this.InitPage();
    }
}
export abstract class LibrarySample extends LibrarySampleBase {
    // no exist ngOnInit()
}
@Component({
    selector: 'app-sample',
    templateUrl: './sample.component.html',
    styleUrls: ['./sample.component.css']
})
export class Sample extends LibrarySample {
    InitPage() {
        // processing
    }
}

How can I get ngOnInit to be called even when ng build --prod=true? Also, please let me know if you have any bug information.

Upvotes: 1

Views: 297

Answers (1)

Daniel Piñeiro
Daniel Piñeiro

Reputation: 3149

This is working for me:

  • library-sample-base.ts
    import { OnInit } from '@angular/core';
    export abstract class LibrarySampleBase implements OnInit {
        public ngOnInit() {
            this.initPage();
        }
        initPage() {
            console.log('Hi');
        }
    }
    export abstract class LibrarySample extends LibrarySampleBase {}
  • app.component.ts
    import { Component } from '@angular/core';
    import { LibrarySample } from './library-sample-base.ts';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent extends LibrarySample {

      initPage() {
        console.log('Bye!');
      }
    }

Bye is shown as the log in the console. If I comment the initPage() in the AppComponent Hi is logged instead. So I think that works as expected.

  • Angular : 7.2.12
  • Angular CLI : 7.3.8

I'm using ng serve --prod=true to try it.

Upvotes: 1

Related Questions