我有一个使用Angular-CLI创建的简单应用程序,我想重构并将app.component.ts代码移动到单独的组件文件中并开始出现一个令人讨厌的错误:
找不到模块:错误:无法解析'./sb/sb.component.html'(我的SBComponent)。在下面
这就是我所拥有的:
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 {
}
任何帮助将不胜感激!
如果您的组件位于同一目录中,则需要将templateUrl
指向同一文件夹。以下是如何做到这一点:
@Component({
selector: 'app-sb',
templateUrl: './sb.component.html'
})
对于这个问题,这个答案可能会迟到,但这适用于实际面临此问题的其他用户。我们应该对这个问题给出正确答案。
当我们使用外部html和css文件的组件相对路径时,这个问题是众所周知的。只需在组件中添加元数据ModuleId即可解决绝对路径和相对路径的问题。
那么ModuleId做了什么? ModuleId包含组件类的绝对URL [实际加载模块文件时]
在构造组件之前,Angular反射过程和metadata_resolver组件使用此ModuleId值来评估完全限定的组件路径
它非常易于使用。只需在@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 {
}
尝试给出相对路径而不是绝对路径。
它将修复解决方案
喜欢:componentUrl ='../employee/employee.html'在你的component.ts中