2017-07-01 15 views
2

我想從另一個組件調用showmodel(displayType)。如何將頭組件函數調用到另一個組件?如何在角度2中將頭部組件函數調用到另一個組件?

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 { 

} 

回答

2

化妝在父組件中使用viewChild。

在您的應用程序組件

-

@ViewChild(HeaderComponent) headerComponent : HeaderComponent; 

然後用

headerComponent.headerMethodName(); 

從HeaderComponent要調用任何方法。

+0

即時獲取'[ts]屬性'showmodel'在類型'typeof HeaderComponent'上不存在'。錯誤 – vel

+1

https://plnkr.co/edit/r9nmdmO0aZHqEbNft7EN?p=preview –

+0

非常感謝。工作正常。 – vel

1

您將需要使用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> 
+0

我試過這樣。所述'的console.log(this.evt);'它retun'EventEmitter {_isScalar:假,觀察員:陣列(0),封閉:假,isStopped:假,hasError:假...} 關閉 : 假 hasError : 假 isStopped : 假 觀察員 : 陣列(0) thrownError : 空 __isAsync : 假 _isScalar : 假 __proto__ : Subject' – vel

+0

您是否導入了eventemitter? '@ angular/core'導入{Component,Input,Output,EventEmitter};' –

+0

是的。我導入了所有東西 – vel

0

角度2被迷上了基於組件和組件的交互,瞭解數據是如何從一個組件傳遞到另一個是很重要的。數據通過屬性綁定在組件之間傳遞。看看下面的語法:

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

值電流分量和用戶的屬性是一個屬性訪問的另一個組件

您應該使用@input財產

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

export Class exampleComponent{ 
    @Input() user: any ; 
} 
+0

我想從一個函數調用函數組件到另一個組件 – vel

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') 

    } 

} 

Services永遠是最好的選擇(有時甚至是唯一的選擇),當它涉及到組件通信。

使用上述服務,可以隱藏標頭的組件不必瞭解對方,並且可以使它們完全可重用。

而且,如果您的組件被銷燬,請不要忘記取消訂閱您的服務。

內部訂閱SharedService$onHide方法的任何組件。

ngOndestroy(){ 
    this.subs.unsubscribe(); 
} 
相關問題