Skip to content

bug(Lifecycle): Lifecycle hooks not called unless defined on the prototype #7270

Closed

Description

@brandonroberts

The lifecycle hooks (component, router) are called if defined on the class, or the function prototype, but are not called if defined in the constructor.

class MyComponent implements OnInit {
    ngOnInit() { 
        // works
    }
}

class MyComponent implements OnInit {
    ngOnInit: any = () => {
         // no TypeScript warning, never called
    }
}

function MyComponent() {
}

MyComponent.prototype.ngOnInit = function() {
    // works
};

function MyComponent() {
    this.ngOnInit = function() {
        // never called
    };
}

I expect the lifecycle hook to be called in either scenario. Is this by design?

cc: @mhevery

Activity

  1. ValeriiVasin commented on Mar 2, 2016

    @ValeriiVasin

    Have the same issues with lifecycle hooks. That was totally unexpected...

    Will it be fixed?

    BTW, React lifecycle hooks behave the expected way.

  2. wardbell commented on Mar 23, 2016

    @wardbell
    Contributor

    Easy to guess why as it would be safer to analyze a prototype and store the information about the component rather than instantiate one (risk of it doing something in the ctor) to find out what it has.

    What use cases argue for this proposal? Isn't it fairly easy to workaround?

  3. mhevery commented on Mar 25, 2016

    @mhevery
    Contributor

    Sorry, this is working as intended. The reason for this is that we need to code-gen different code depending if we have such a hook or not. Code-gen can only access the prototype chains, as we can't instantiate/run code. So if you want speed, prototype is the only thing we can look at.

  4. angular-automatic-lock-bot commented on Sep 8, 2019

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  5. locked and limited conversation to collaborators on Sep 8, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions