ng-init Similar Functionality in Angular2

2,686 views
Skip to first unread message

Sourav Dutta

unread,
May 1, 2016, 4:34:38 PM5/1/16
to AngularJS
I need to know, How can I achieve similar functionality in angular2. 

Thanks,
Sourav Dutta

Zlatko Đurić

unread,
May 2, 2016, 4:22:45 AM5/2/16
to AngularJS
On Sunday, May 1, 2016 at 10:34:38 PM UTC+2, Sourav Dutta wrote:
I need to know, How can I achieve similar functionality in angular2. 


There are several ways, depending on what you need. The simplest being - just asign the value in the constructor. But also take a look at Lifecycle hooks: https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html.

I would suggest either ngOnInit, ngAfterContentInit or ngAfterViewInit, again depending on what you want to achieve. Example with onInit:

import {Component, OnInit} from 'angular2/core';
@Component({
  selector: 'my-component',
  template: '<p>{{ message.text }} </p> <p> {{ message.num }} </p>'
})
class MyComponent implements OnInit {

    ngOnInit() {
        this.message = {
            text: 'Hello there!',
            num: 4
        };
  }
}
Reply all
Reply to author
Forward
0 new messages