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 { 

}

5 Answers 5

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();
}
Sign up to request clarification or add additional context in comments.

3 Comments

This is the perfect way to get data from one independent component to other.
Nice answer. very helpful
So on page refresh, all data will be lost? how to keep the data even if a page is refreshed?
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.

2 Comments

im getting [ts] Property 'showmodel' does not exist on type 'typeof HeaderComponent'. error
where i have to use headerComponent.headerMethodName();
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>

8 Comments

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
Did you import eventemitter ? import { Component, Input, Output, EventEmitter } from '@angular/core';
Yes. i imported all the things
(evt)="com1.showmodel($event)" where its come from com1?
com1 should be the component selector where actual function exists,in this case selector for header component
|
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 ;
}

1 Comment

I want to call function from one component to another component.
0

just use this code: in your component

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

and then use:

this.headerComponent.anyheaderMethod();

this will help definitly

1 Comment

It is very late answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.