Angular 2 – Two Ways to Initialize Component Properties

1
This article represents two different ways in which Angular 2 components properties can be initialized. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos.
Following are two different ways to initialize the component properties.

  • In the example below, component’s property is initialize through variable assignment. Take a look at the code “name = ‘Calvin Hobbes'”. This approach is sometimes preferable because it makes code easy to read and also, there will be lesser code to write.
    import {Component, View} from 'angular2/core';
    
    @Component({
      selector: 'user'
    })
    @View({
      template: '{{name}}'
    })
    export class UserComponent {
      name = 'Calvin Hobbes';
    }
    
  • In the code below, the property is first declared and then initialized inside the constructor.
    import {Component, View} from 'angular2/core';
    
    @Component({
      selector: 'user'
    })
    @View({
      template: '{{name}}'
    })
    export class UserComponent {
      name: string;
    
      constructor() {
        this.name = 'Calvin Hobbes';
      }
    }
    

 

Ajitesh Kumar

Ajitesh Kumar

Ajitesh is passionate about various different technologies including programming languages such as Java/JEE, Javascript, PHP, C/C++, mobile programming languages etc, and, computing fundamentals related with cloud-native technologies, application security, cloud computing platforms, mobile apps, big data etc.

He has also authored the book, Building Web Apps with Spring 5 and Angular.
Ajitesh Kumar

1 Comment

  1. nice blog too informative. looking and reading your points its so impressive. doing more blog like this. i really appreciated doing like this.

Leave A Reply

Time limit is exhausted. Please reload the CAPTCHA.