How to set default values for Angular 2 component properties?

In Angular 2, we can pass the value of a variable between two components (from parent to child) using the Input Decorator. Using these Input decorators we can also set the default values of the properties. Below I had detailly elaborated in a comprehensive way on how to set default values for Angular 2 component.

Syntax:

@Input() PropertyName = Default Value  /* @Input country = 'India' */

    Approach:

  • First code the .html file with respect to requirements.
  • Then include the default property in the child component.
  • Now initialize the property with a default value using the @Input() decorator.
  • We should also import the Input decorator from ‘@angular/core’.
  • Once initialization is completed, use the property in HTML file to display in the browser.

Syntax for importing:

import { Input } from '@angular/core';

Implementation by code:
app.component.html:



filter_none

edit
close

play_arrow

link
brightness_4
code

<p>Welcome to GeeksforGeeks </p>
<app-child [country] = "countryName"></app-child>

chevron_right


app.component.ts:
 

filter_none

edit
close

play_arrow

link
brightness_4
code

import { Component } from '@angular/core';
  
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  constructor() { }
  ngOnInit() {}
  countryName = 'India';
}

chevron_right


child.component.ts:

filter_none

edit
close

play_arrow

link
brightness_4
code

import { Component, Input, OnInit} from '@angular/core';
  
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html'
})
export class ChildComponent implements OnInit {
  constructor() { }
  ngOnInit() {}
    
  @Input() country = 'Australia';
  @Input() capital = 'New Delhi';
  
}

chevron_right


child.component.html:

filter_none

edit
close

play_arrow

link
brightness_4
code

<p> Country is : {{country}} </p>
<p> Capital is : {{capital}} </p>

chevron_right


Conclusion:
As we are passing country property as ‘India’, it will be displayed. But when it comes to capital as we are not passing any value it displays the default value in child.component.ts file.

Output:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.