Friday, January 19, 2018

Passing Data from Parent To Child Angular 2

Let's First  create a basic component

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

@Component(

selector : 'child-selector',
template : 'child.component.html'
})


export class ChildComponent
{
}

And child.component.html is

<p>
  child.component works! Value get from parent is : {{title}}
</p>



And Parent Component is

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

@Component(
{
selector : 'parent-selector',
template : parent.component.html"
}
)

export class ParentComponent
{

parentTitle:string ="ParentTitle";
}


And parent.component.html is

<p>
  parent.component works!
</p>

<app-child-component [title]="parentTitle"></app-child-component>



Now if you want to pass data from parent to child you have to use @Input decorator in child component as below

export class ChildComponent
{

@Input() title : string;

}

And parent should be like this

import {Component} from '@angular/core'

@Component(

selector : 'parent-selector',
template : 'parent.component.html',
directives : [ChildComponent]

}
)
export class ParentComponent
{

childTitle : String ="This will be passed to child";

}

parent.component.html file is

<p>
  parent.component works!
</p>

<app-child-component [childTitle]="parentTitle"></app-child-component>


No comments:

Followers

Link