2

I want to call showmodel(displayType) from another compoent.How to call header component function to another component?

header.compoent.ts

    import { Component,Renderer } from '@angular/core';
    import { Title,DOCUMENT  } from '@angular/platform-browser';
    import { CountriesService } from '../services/countries.services';
    import { Router,ActivatedRoute, Params } from '@angular/router';
    import {  AuthenticationService } from '../services/authentication.service';
    import { Observable } from 'rxjs/Observable';
    import {FacebookService, InitParams, LoginResponse,LoginOptions} from 'ngx-facebook';


    @Component({
      moduleId: module.id,
      selector: 'app-header',
      templateUrl: 'header.component.html',
      styleUrls: ['../app.component.css'],
    })
    export class HeaderComponent {    


        public visible = false;
        public visibleAnimate = false;
        public visibleRegister = false;
        public visibleAnimateRegister = false;

        registerformcont= false;
        registerActive = true;
        loginactive = false;
        currentUser: any = {};
        PopupTitle='';
        callBackfunc='';
        responseNameCheck:any={};
        LoginOptions:any={};
        response:any={};
        FacebookResponse:any={};

     constructor(
            title: Title,
            private countriesService: CountriesService,
            private Router: Router,
            private authenticationService: AuthenticationService,   
            private fb: FacebookService

     ) {  

        let initParams: InitParams = {
          appId      : '*********',
          cookie     : true,
          xfbml      : true,
          version    : 'v2.8'
        };

        fb.init(initParams);

            Router.events.subscribe((val) => {
                 this.searchResultCont  = false;    
                  this.showStyle = false;  
                });
     }

    ngOnInit() {    

            this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
            if(this.currentUser){
                this.loginStatus = this.currentUser.status;
            }
    }




        public showmodel(displayType): void {


            this.visible = true;                    
            this.visibleAnimate = true

      }


      public hide(): void {
          this.visibleAnimate = false;          
          setTimeout(() => this.visible = false, 300);      
      }



    }

app.component.ts

 @Component({ 
  selector: 'my-app',
  template: `
    <app-header></app-header>
    <router-outlet></router-outlet>    
    <app-footer></app-footer>`,
  styleUrls: ['../app/app.component.css'],
})

export class AppComponent { 

}
Vel
  • 9,027
  • 6
  • 34
  • 66

5 Answers5

9

if there is no direct parent child relation between this two, you've got to use a shared service and an eventEmitter to pass values.

@Component({
  moduleId: module.id,
  selector: 'app-header',
  templateUrl: 'header.component.html',
  styleUrls: ['../app.component.css'],
})

export class HeaderComponent {    
  this.subs    
  constructor(private sharedService:SharedService){

  this.subs = this.sharedService.onHide$.subscribe(()=>{ 
      this.hide(); 
    });
  }
}

And then your SharedService is :

@Injectable()
export class SharedService{
  public onHide$ = new EventEmitter<boolean>()
}

@Component({})
export class YourOtherComponent{
  constructor(private sharedService:SharedService){ }

  hideIt(){
    this.sharedService.onHide$.emit('hide it baby')
  }
}

Angular Services are always the best option (and sometimes the only option) when it comes to component communication.

With above service, component's who can hide your header don't have to know about each other and you can make them completely reusable.

And, don't forget to unsubscribe from your services if your component is destroyed.

inside any of the components who subscribe to SharedService's $onHide method.

ngOndestroy(){
  this.subs.unsubscribe();
}
Nils Kähler
  • 2,645
  • 1
  • 21
  • 26
Milad
  • 27,506
  • 11
  • 76
  • 85
3

make use of viewChild in your parent component.

in your app component -

@ViewChild(HeaderComponent) headerComponent : HeaderComponent;

then use

headerComponent.headerMethodName(); 

any method from HeaderComponent you want to invoke.

Rahul Singh
  • 341
  • 1
  • 6
1

You will need to use EventEmitter.

@component({
  selector:'app-header',
})
export class HeaderComponent {

  public showmodel(displayType): void {
        this.visible = true;                    
        this.visibleAnimate = true
  }

}

Now say in second component you emit the event on a button click.

@component({
  selector:'another component',
  template: `<button (click)="callShowModel()">click</button>`
)
export class com2{
  @Output() evt = new EventEmitter();
  callShowModel(){
     this.evt.emit(<value>);
  }
}

Now your event can be hooked up in parent component

<headercomponent (evt)="showmodel($event)"></headercomponent>
Navoneel Talukdar
  • 4,393
  • 5
  • 21
  • 42
  • I tried like this. the `console.log(this.evt);` it retun `EventEmitter {_isScalar: false, observers: Array(0), closed: false, isStopped: false, hasError: false…} closed : false hasError : false isStopped : false observers : Array(0) thrownError : null __isAsync : false _isScalar : false __proto__ : Subject` – Vel Jul 01 '17 at 06:18
  • Did you import eventemitter ? `import { Component, Input, Output, EventEmitter } from '@angular/core';` – Navoneel Talukdar Jul 01 '17 at 06:23
  • Yes. i imported all the things – Vel Jul 01 '17 at 06:25
  • `(evt)="com1.showmodel($event)"` where its come from `com1`? – Vel Jul 01 '17 at 06:26
  • com1 should be the component selector where actual function exists,in this case selector for header component – Navoneel Talukdar Jul 01 '17 at 06:28
  • `(evt)="app-header.showmodel($event)` this is fine? – Vel Jul 01 '17 at 06:29
  • If both of your components are siblings no need to use selector,see edit – Navoneel Talukdar Jul 01 '17 at 06:33
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/148105/discussion-between-vel-and-neel). – Vel Jul 01 '17 at 06:34
0

As Angular 2 is based on components and component interaction, it is important to understand how data is passed from one component to another. Data is passed between components using property bindings. Take a look at the syntax below:

<user [value]="user"></user>

value is a property of current component and user is a property for access another component

you should use to @Input property

import {Component, Input} from 'angular2/angular2'

export Class exampleComponent{
  @Input() user: any ;
}
Mahesh Bhattarai
  • 722
  • 7
  • 16
0

just use this code: in your component

@ViewChild(HeaderComponent, { static: true }) headerComponent: HeaderComponent;

and then use:

this.headerComponent.anyheaderMethod();

this will help definitly