【问题标题】:How to call header component function to another component in angular 2?如何将标题组件功能调用到角度 2 中的另一个组件?
【发布时间】:2017-12-05 01:58:06
【问题描述】:

我想从另一个组件调用showmodel(displayType)。如何调用头组件函数到另一个组件?

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 { 

}

【问题讨论】:

    标签: angular


    【解决方案1】:

    如果这两者之间没有直接的父子关系,则必须使用共享服务和 eventEmitter 来传递值。

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

    然后你的 SharedService 是:

    @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 始终是最佳选择(有时是唯一选择)。

    通过上述服务,可以隐藏标题的组件不必相互了解,您可以使它们完全可重用。

    而且,如果您的组件被销毁,请不要忘记取消订阅您的服务。

    在订阅SharedService$onHide 方法的任何组件内。

    ngOndestroy(){
      this.subs.unsubscribe();
    }
    

    【讨论】:

    • 这是从一个独立组件获取数据到另一个组件的完美方式。
    • 不错的答案。很有帮助
    • 所以在页面刷新时,所有数据都会丢失?页面刷新后如何保留数据?
    【解决方案2】:

    在你的父组件中使用 viewChild。

    在您的应用组件中 -

    @ViewChild(HeaderComponent) headerComponent : HeaderComponent;
    

    然后使用

    headerComponent.headerMethodName(); 
    

    您要调用的 HeaderComponent 中的任何方法。

    【讨论】:

    • 我收到[ts] Property 'showmodel' does not exist on type 'typeof HeaderComponent'. 错误
    【解决方案3】:

    您需要使用EventEmitter

    @component({
      selector:'app-header',
    })
    export class HeaderComponent {
    
      public showmodel(displayType): void {
            this.visible = true;                    
            this.visibleAnimate = true
      }
    
    }
    

    现在在第二个组件中说,您在单击按钮时发出事件。

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

    现在你的事件可以挂在父组件中

    <headercomponent (evt)="showmodel($event)"></headercomponent>
    

    【讨论】:

    • 我试过这样。 console.log(this.evt);它返回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
    • 你导入了 eventemitter 吗? import { Component, Input, Output, EventEmitter } from '@angular/core';
    • 是的。我进口了所有的东西
    • (evt)="com1.showmodel($event)" 来自com1
    • com1 应该是实际功能所在的组件选择器,这里是头部组件的选择器
    【解决方案4】:

    由于 Angular 2 基于组件和组件交互,因此了解数据如何从一个组件传递到另一个组件非常重要。使用属性绑定在组件之间传递数据。看看下面的语法:

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

    value 是当前组件的属性,user 是访问另一个组件的属性

    你应该使用@Input属性

    import {Component, Input} from 'angular2/angular2'
    
    export Class exampleComponent{
      @Input() user: any ;
    }
    

    【讨论】:

    • 我想从一个组件调用函数到另一个组件。
    【解决方案5】:

    只需使用以下代码:在您的组件中

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

    然后使用:

    this.headerComponent.anyheaderMethod();

    这绝对有帮助

    【讨论】:

    • 回答太晚了。
    猜你喜欢
    • 2018-07-07
    • 2020-02-25
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    相关资源
    最近更新 更多