2016-09-14 25 views
0

は私がルートフォルダに別のファイルにコンポーネントを定義します。Angular2でコンポーネントを参照するにはどうすればよいですか?

import {Component} from '@angular/core' 

@Component({ 
    selector: 'testtag', 
    templateUrl: './simplecomponent.component.html', 
}) 

export class SimpleComponent { 

} 

私は、主成分はそうと同じように使用できるように、それをインポートしよう:

import {SimpleComponent} from './simplecomponent.component.ts' 

を、私はその後、取得次のエラー:

VM360 zone.js:192 Error: (SystemJS) ReferenceError: SimpleComponent is not defined

ここにはPLUNKがあります。関連するコードはsrc/app.tsにあります。ここでコメントを外すとSimpleComponentが動作することに注意してください。問題はそれを別のファイルに移動して参照していることに注意してください。

また、コンポーネントをモジュールに「アタッチ」する方法もあります。角度1では、私はちょうどでした:

angular.module('myApp').controller(name, function); 

が、それは関係なく、ファイルが置かれている場所の、declarationsにそれを追加するだけですか?

@NgModule({ 
    imports: [ BrowserModule ], 
    declarations: [ SimpleComponent ], 
    bootstrap: [ App ] 
}) 

答えて

1

参照したいコンポーネントファイルの相対パスに注意してください。 ./と../とdirの名前を使用して、参照ファイルを現在のファイルの場所から見つける場所を示します。たとえば、あなたがComponentA内ComponentBをインポートしようとしている場合:両方のコンポーネントファイルが同じディレクトリにある場合

  • 、ComponentAに次のものが必要です。

    import { ComponentB } from './componentB';

    (./の略"これと同じディレクトリ")

  • ComponentBがComponentAの親ディレクトリにある場合は、次のものが必要です。

    import { ComponentB } from '../componentB';

    (../ ../../は "祖父母ディレクトリ" の略ながら、 "親ディレクトリ" の略で、など)。

  • ComponentBがComponentAが配置されている場所のサブディレクトリにある場合、あなたは現在のディレクトリ(./)から開始し、そのディレクトリの名前を言及する必要があります。

    import { ComponentB } from './subDirB/componentB';

  • ComponentBがオンになっている場合ComponentAが配置されている場所の兄弟ディレクトリ、あなたは物事をミックスする必要があります。

    import { ComponentB } from '../subDirB/componentB';

1

あなただけ間違ってあなたのパスだ...

import {SimpleComponent} from '../simplecomponent.component.ts' 

あなたapp.tsはsimplecomponent.component.tsより1つのディレクトリ低い - パスが相対的です。

関連する問題