2016-11-02 25 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' 

现在打字稿有工作参考类,但只有一个组件需要引用功能模块,而不是单个组件。