Pass variable from parent to custom child component – Angular 9

Pass variable from parent to custom child component – Angular 9 ?

This tutorial guides you on how to pass variable from parent to custom child component in Angular 9 application. Let’s see an Angular 9 example code for custom components and databinding, and you will also learn how to pass data from parent component to a child component.

Pass variable from parent to custom child component – Angular 9

The following is an Angular example code for custom components and data binding. In this example, we are allowing user to define item name or title and item description. And you can add either item or item specifications as shown in the following picture.

For example, let’s say a separate component is created for a section, where we enter item name and item description with buttons. Let’s call it as “create-item” component.

Also a separate component is created for individual items that are getting generated/added dynamically. let’s call it as “item-element” component. And app component is our parent component.

Pass variable from parent to custom child component – Angular 9

How to pass data from parent to custom components ?

In below code sneppets if you see the code in the “item-element” component typescript file, we had marked the class field as an input property using @Input Decorator as shown below.

Therefore, the alias “itemElement” to the custom property is marked as input property and this property is bound to DOM property defined in the app.component.html (parent) i.e.,  [itemElement].

Basically, what you need to do is, you need to add input property using @Input decorator in the child component class to receive the data that is passed from parent component.

export class ItemElementComponent implements OnInit {

  @Input('itemElement') itemElem : {type: string, title: string, desc: string, spec: string};

  constructor() { }

  ngOnInit(): void {
  }

}

Next, you need to use property binding in the parent component’s template to pass variable or data from parent to custom child component as shown below

<app-item-element *ngFor="let elem of itemElems"
                        [itemElement] = "elem"></app-item-element>

Here ( [itemelement] = “elem”)  is nothing but Property Binding i.e., ( [property] = “data” ).

You can clearly see that the input property “itemElement” defined in the ItemElemenComponent class is bound to a DOM property (itemElement) in the template.

Therefore, whenever the change is detected, Angular automatically updates the data property defined in the component class with the DOM property’s value.

Pass variable from parent to child components – Example

The following codes are the complete code sneppets for the above example output depicted in the diagram.

Below are the code sneppets for parent component and “create-item” & “item-element” components (child components).

app.component.html

<div class="container">
  <app-create-item (itemAdded)="onItemAdded($event)"
                   (itemSpecAdded)="onItemSpecAdded($event)"></app-create-item>
  <hr>
  <div class="row">
    <div class="col-xs-12">
      <app-item-element *ngFor="let elem of itemElems"
                        [itemElement] = "elem"></app-item-element>
    </div>
  </div>
</div>

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  itemElems = [{type: 'item', title:'Google Pixel', desc:'Android phone by Google', spec:''},
  {type: 'spec', title:'Specifications', desc:'', spec:"Specifications of Google Pixel"}];

  onItemAdded(itemData:{itemTitle: string, itemDesc: string}) {
    this.itemElems.push({
      type: 'item',
      title: itemData.itemTitle,
      desc: itemData.itemDesc,
      spec:''
    });
  }

  onItemSpecAdded(itemSpecData:{itemTitle: string, itemSpec: string}) {
    this.itemElems.push({
      type: 'spec',     
      //title: itemSpecData.itemTitle,
      title: 'Specifications',
      desc:'',
      //spec: itemSpecData.itemTitle
      spec: 'Specifications of '+ itemSpecData.itemTitle
    });
  }
  
}

create-item.component.html

<div class="row">
    <div class="col-xs-12">
      <p>Create Items and Specifications!</p>
      <label>Item Name</label>
      <input type="text" class="form-control" [(ngModel)]="newItemName">
      <label>Item Description</label>
      <input type="text" class="form-control" [(ngModel)]="newItemDesc">
      <br>
      <button
        class="btn btn-primary"
        (click)="onAddItem()">Add Item</button>
      <button
        class="btn btn-primary"
        (click)="onAddItemSpec()">Add Item Specifications</button>
    </div>
  </div>

create-item.component.ts

import { Component, OnInit, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-create-item',
  templateUrl: './create-item.component.html',
  styleUrls: ['./create-item.component.css']
})
export class CreateItemComponent implements OnInit {

  @Output() itemAdded = new EventEmitter<{itemTitle: string, itemDesc: string}>();
  @Output() itemSpecAdded = new EventEmitter<{itemTitle: string, itemSpec: string}>();

  newItemName = '';
  newItemDesc = '';
  newItemSpec = '';

  constructor() { }

  ngOnInit(): void {
  }

  onAddItem() {
    this.itemAdded.emit({
        itemTitle: this.newItemName, 
        itemDesc: this.newItemDesc
    });
  }

  onAddItemSpec() {
    this.itemSpecAdded.emit({
      itemTitle: this.newItemName, 
      itemSpec: this.newItemSpec
    });
  }

}

item-element.component.html

<div
class="panel panel-default">
<div class="panel-heading">{{ itemElem.title }}</div>
<div class="panel-body">
  <p>
    <strong *ngIf="itemElem.type === 'item'" style="color: orange">{{ itemElem.desc }}</strong>
    <em *ngIf="itemElem.type === 'spec'">{{ itemElem.spec }}</em>
  </p>
</div>
</div>

item-element.component.ts

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

@Component({
  selector: 'app-item-element',
  templateUrl: './item-element.component.html',
  styleUrls: ['./item-element.component.css']
})
export class ItemElementComponent implements OnInit {

  @Input('itemElement') itemElem : {type: string, title: string, desc: string, spec: string};

  constructor() { }

  ngOnInit(): void {
  }

}

That’s it. Hope you had learnt about custom components and data binding.

Now you know how to pass variable or data from parent to custom child component in an Angular 9 application.

Hope it helped 🙂

Also See:

References:

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments