2016-11-02 107 views
2

我是新的角2,所以請原諒,如果這個問題聽起來微不足道。我正在創建一個角度爲2的特徵模塊,我將從該模塊中導出所有組件。主模塊可以導入它並在導入列表中添加此模塊。通過這樣做,主模塊中的所有「模板」都可以訪問特徵模塊的組件。如何從角度2中的不同模塊訪問組件

但我想要的是:在我的主要模塊組件之一中,我想將特徵模塊的組件稱爲ViewChild。

回答

1

你需要用打字稿進口導入組件類像

import {MyComponent} from './my.component' 

那麼你可以使用它在@ViewChild()

@ViewChild(MyComponent) myComponent:MyComponent; 
+0

是否有權從不同的模塊訪問內部文件?如果它在同一個模塊中,這看起來很好。如果我這樣做,爲什麼我需要將它放在功能模塊的導入列表中。 – Pragmatic

+0

我不確定你的意思。這是如何完成的。 –

+0

你可能是對的。但是你根本沒有使用模塊特性。你只是繞過模塊。正如我以前寫過的,如果組件不在要素模塊的導出列表中,它會起作用嗎?我想,它會的。 – Pragmatic

0

請考慮創建一個共享模塊(功能),它將提供該組件到這兩個模塊。請參閱官方documents用於使用共享模塊構建應用程序

0

ViewChild是一個裝飾器,您可以使用它來查詢模板以獲取從功能模塊導入的子模板。 如果模板是:

<div> 
    <child></child> 
</div> 

使用@ViewChild,你可以讓你的孩子組件參考

+0

對不起,我無法得到它。您能否請詳閱 – Pragmatic

0

您可以使用服務和EventEmitter爲此。

import { Injectable, EventEmitter } from '@angular/core'; 


    @Injectable() 
    export class MyService { 

     resultIdFound: EventEmitter<any> = new EventEmitter<any>(); 

     resultFound(resultId: string) { 
      this.resultIdFound.emit(resultId) 
     } 
    } 

源組件是:

import { Component, EventEmitter } from '@angular/core'; 
import { MyService } from './myservice'; 

    @Component({ 
    //.. 
    }) 
    export class SourceComponent implements OnInit { 
     constructor(
      private router: Router, 
      private myService: MyService) { } 

     onResultFound(resultId: string): void { 

      this.myService.roomSeached(this.selectedRoom.id) 
     } 
    } 

和目標組件是:

import { Component, EventEmitter,NgModule } from '@angular/core'; 
import { MyService } from './myService'; 

    @Component({ 
    //... 
    }) 
    export class TargetComponent implements OnInit { 
     constructor( 
      private myService: MyService 
     ) { 
      this.myService.resultIdFound.subscribe((result: any) => { 
       console.log(result) 
      }); 

     }  
     //....  
    } 
+0

感謝您的回答!但這是一個可以在不同組件之間進行通信的工作。您的意思是來自模塊的組件不能使用ViewChild從不同模塊訪問另一個組件? – Pragmatic

2

@ViewChild可以與本地ID(以#前綴)使用,而你不必須導入定義類。當然,你不能再輸入變量comp作爲MyComponent

在模板:

<my-component #myComponent></my-component> 

在JavaScript:

@ViewChild('myComponent') comp: any; 

(注意引號)

或者
可以重新EXP ORT從功能模塊

// my.module.ts 

import {MyComponent} from './my.component' 

@NgModule({ 
    ... 
}) 
export class MyModule {} 
export {MyComponent} 

然後在消耗組件(要使用@ViewChild)

import {MyComponent} from '../common/my.module' 

現在打字稿有工作參考類,但只有一個組件需要引用功能模塊,而不是單個組件。