The order of execution - FadiZahhar/switchingtoangular2 GitHub Wiki

In order to trace the order of execution of the callbacks associated with each hook, let's take a peek at the ch4/ts/life-cycle/app.ts example: @Component({ selector: 'panel', inputs: ['title', 'caption'], template: '' }) class Panel { ngOnChanges(changes) {…} ngOnInit() {…} ngDoCheck() {…} ngOnDestroy() {…} ngAfterContentInit() {…} ngAfterContentChecked() {…} ngAfterViewInit() {…} ngAfterViewChecked() {…} } The Panel component implements all the hooks without explicitly implementing the interfaces associated with them.

We can use the component in the following template: <button (click)="toggle()">Toggle

Hello world!
In the preceding example, we have a panel and a button. Upon each click on the button, the panel will be either removed or appended to the view by the ngIf directive. During the application initialization, if the result of the "counter % 2 == 0" expression is evaluated to true, the ngOnChanges method will be invoked. This happens because the values of the title and caption properties are going to be set for the first time. Right after this, the ngOnInit method will be called, since the component has been initialized. Once the component's initialization is completed, the change detection will be triggered, which will lead to the invocation of the ngDoCheck method that allows us to hook custom logic for detecting changes in the state. Note that you are not supposed to implement both ngDoCheck and ngOnChanges methods for the same component, since they are mutually exclusive. The example here does this for learning purposes only. After the ngDoCheck method, the component's content will be followed by performing a check on it (ngAfterContentInit and ngAfterContentChecked will be invoked in this order). Right after this, the same will happen for the component's view (ngAfterViewInit followed by ngAfterViewChecked). Once the expression of the ngIf directive is evaluated to false, the entire component will be detached from the view, which will lead to the invocation of the ngOnDestroy hook. On the next button click, if the value of the expression of ngIf is equal to true, the same sequence of calls of the life cycle hooks as the one during the initialization phase will be executed.
⚠️ **GitHub.com Fallback** ⚠️