Thursday, 15 December 2016

Passing data from Parent to Child Component

Passing data to a nested component

In Angular 1 we used $broadcast, $emit, $on to communicate between controllers. But now in angular 2 we have different approach.

In Angular 2, If you want to flow data from Parent Component to Child Component we use @Input Decorator or "inputs" property inside @Component decorator or in a Class. Hear we will discuss the former approach.

Our Directory Structure

Parent Component

//our root app component
import { Component, NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { FormsModule }   from '@angular/forms';
import { ChildComponent } from './child.component';
import { Character } from './character';

@Component({
  selector: 'my-app',
  template: `
  <h1>@input</h1>
  <div style = "border:2px solid orange; padding:5px;">
    <h2>Parent Component</h2>
    <input [(ngModel)] = "characters[0].name"/>
    <button (click)="select(characters[0])">Input</button>
    <br/><br/> 
    <child-component [character]="selectedCharacter"></child-component>
  </div>
  `,
})
export class App {
  characters = [
    {
      "id":11,
      "name":"Name"
    }];
     
    selectedCharacter: Character;
    
    select(selectedCharacter : Character){
      this.selectedCharacter = selectedCharacter;
    }
}

@NgModule({
  imports: [ BrowserModule,FormsModule  ],
  declarations: [ App, ChildComponent ],
  bootstrap: [ App ]
})
export class AppModule {}

Child Component

import { Component, Input} from '@angular/core';
import { Character} from './character';
@Component({
  selector: 'child-component',
  template:`
  <div style="border:2px solid orange; padding:5px">
    <h2>Child Component: <span *ngIf="character">{{character.name}}</span></h2>
  </div>
  `
})
export class ChildComponent {
   @Input() character: Character;
}

Full source

Find full source from my github

No comments:

Post a Comment