How to call header component function to another component in angular 2?

后端 未结 5 937
别跟我提以往
别跟我提以往 2021-01-22 07:24

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

header.compoent.ts

5条回答
  •  温柔的废话
    2021-01-22 08:00

    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()
    
    }
    
    
    
    @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();
    }
    

提交回复
热议问题