How to pass data from Component to Directive in Angular 2

2016-09-11 23:05:34

1- in Component file define @Output() like below:

import {Header} from "../header/header.directives";

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

@Component({ directives: [Header], templateUrl: "home.template.html" }) export class HomeComponent { @Output() eventEmitter : EventEmitter<boolean> = new EventEmitter<boolean>(); constructor() {
}


ExpFunc(val:boolean){

eventEmitter.emit(val); 


} }



2-in Directive file define @Input() like below:

import {Directive,Input} from "@angular/core";

@Directive({

selector:"[header]"

})

 

export class Header {

@Input() set eventListener (val){

            val.subscribe((param:boolean)=>{

         this.doSomeThing(param);

    });
}

constroctor(){



}

doSomeThing(val){
console.log(val);

}

}

 

3-in the home.template.html add Output like below:

 

<div class="headerClass" header [eventListener]="eventEmitter"></div> 

demo on github: https://github.com/sadeghipour/angular2-examples

Tags Cloud

Angular2

Component

Directive

Typescript

pass data

Webpack starter