Angular 2:找不到模块:错误:无法解析

Angular 2:找不到模块:错误:无法解析

问题描述:

我有一个使用Angular-CLI创建的简单应用程序,我想重构app.component.ts代码并将其移动到单独的组件文件中,并开始变得讨厌错误:Angular 2:找不到模块:错误:无法解析

Module not found: Error: Can't resolve on './sb/sb.component.html' ( my SBComponent). Under the

这是我有:

app.module:

import { BrowserModule } from '@angular/platform-browser'; 
import { NgModule } from '@angular/core'; 
import { FormsModule } from '@angular/forms'; 
import { HttpModule } from '@angular/http'; 

import { AppComponent } from './app.component'; 
import { SBComponent } from './sb/sb.component' 

@NgModule({ 
    declarations: [ 
    AppComponent, SBComponent 
    ], 
    imports: [ 
    BrowserModule, 
    FormsModule, 
    HttpModule 
    ], 
    providers: [], 
    bootstrap: [AppComponent] 
}) 
export class AppModule { } 

app.component:

import { Component } from '@angular/core'; 
import { NgModule,ElementRef, ViewChild, AfterViewInit} from '@angular/core' 
import {BrowserModule} from '@angular/platform-browser' 


@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 


} 

新组件:

import { Component, OnInit } from '@angular/core'; 
import { NgModule,ElementRef, ViewChild, AfterViewInit, AfterContentInit} from '@angular/core' 
import {BrowserModule} from '@angular/platform-browser' 


@Component({ 

    selector: 'app-sb', 
    templateUrl: './sb/sb.component.html' 
}) 
export class SBComponent { 



} 

任何帮助将不胜感激!

+1

'sb.component.html'存在sb文件夹中?如果它们都在同一个文件夹中,则尝试使用'./sb.component.html' –

+0

是的,它存在于sb文件夹中,app.ts存在于该文件夹之外。 'SBComponent'中的 – eagleEye

+4

将'templateUrl'改为'templateUrl:'。/ sb.component.html'' –

如果您的组件位于同一个目录中,那么您需要将您的templateUrl指向同一个文件夹。下面是你如何做到这一点:

@Component({ 
    selector: 'app-sb', 
    templateUrl: './sb.component.html' 
}) 

这个问题可能会迟到这个问题,但这是其他用户谁真正面临这个问题。我们应该需要给出正确的答案。到这样的问题。

当我们使用外部html和css文件的组件相对路径时,这个问题是非常知道的。只需在组件中添加元数据ModuleId即可解决绝对路径和相对路径的问题。

现在ModuleId做什么?的moduleId包含组件类[当模块文件被实际装载]

ModuleId值用于由角反射过程和metadata_resolver组件的组件之前评估完全合格的组件路径的绝对URL

它非常容易使用。只需在@Component装饰中添加一个条目即可。完整的代码如下。

@Component({ 
    moduleId: module.id, // fully resolved filename; defined at module load time 
    selector: 'app-sb', 
    templateUrl: 'sb.component.html' //Observe this. 
}) 
export class SBComponent { 

} 
+0

这是为我工作:@Component({ 的moduleId:module.id, 选择: '我-演示', templateUrl: './input-text-validation.html' }) –