2017-07-01 6 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

メイクを@Inputするために使用する必要があり、別のコンポーネント

アクセスのためのプロパティです親コンポーネントの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 
    } 

} 

ここで、2番目のコンポーネントでは、ボタンをクリックしてイベントを発生させます。

@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);'が '持つEventEmitter retun は 閉じ{_isScalarを:偽、オブザーバー:... FALSE FALSE、isStopped:::偽、hasErrorをアレイ(0)、閉じ} 偽 hasErrorを : isStopped偽: 偽 オブザーバー: アレイ(0) thrownError: ヌル__isAsync : 偽 _isScalar: 偽__proto__ : 件名 ' – vel

+0

eventemitterをインポートしましたか? 'import @ Component、Input、Output、EventEmitter} from '@ angular/core'; ' –

+0

はい。私はすべてのものをインポートしました – vel

0

としてアンギュラ2にフックアップすることができ、そのデータを別のコンポーネントから渡される方法を理解することが重要です。データは、プロパティーバインディングを使用してコンポーネント間を渡されます。以下の構文を見てみましょう:

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

値は、現在のコンポーネントとユーザーの財産であることは、あなたが財産

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

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

を私は1つの関数を呼び出したいです – vel

1

この2つの間に直接の親子関係がない場合は、共有サービスと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(); 
} 
関連する問題