Angular Parent & Child Components

Angular parent and child components, following are the benefits and drawbacks in Parent-Child Components:

1. In Parent Child component,  it is easy to pass data from Parent Component to child component and vice versa.

2. In Parent Child component, we can achieve sub-tasks on Main pages, e.g. in Property website, we can display list of Properties when user will navigate to 'mysite/properties' page and in "AddEditProperty" child Component, we can pass URLs like 'mysite/properties/add' or 'mysite/properties/edit/1', we have to add routing under parent page routing in our routing.ts file.

3. We can have one parent and multiple child components and also we can have one child and multiple parent Components.

e.g.

<app-properties>

  <app-add-properties></app-add-properties>

</app-properties>

Here in above example, "app-properties" is Parent Component and "app-add-properties" is child component.

Passing Input values from Parent to Child Component:

Parent Component Class:

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

@Component({

  selector: 'app-properties',

  templateUrl: './properties.component.html',

  styleUrls: ['./properties.component.css']

})

export class PropertiesComponent {

  propertyTypeList: Array<string> = ["Residential","Commercial"];

  propertyList: Array<string> = ["Property-1","Property-2"];

}

Parent Component Template File:

<app-add-properties [propertyTypes]="propertyTypeList"></app-add-properties>

<h2>All Properties</h2>

<ul *ngFor="let property of propertyList">

    <li>{{property}}</li>

</ul>

Child Component Class:

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

@Component({

  selector: 'app-add-properties',

  templateUrl: './add-properties.component.html',

  styleUrls: ['./add-properties.component.css']

})

export class AddPropertiesComponent {

 @Input() propertyTypes: any;

}

Child Component Template

<div *ngFor="let type of propertyTypes">

    <label><input type="radio" name="propertyType" />{{type}}</label>

</div>

Output