繁体   English   中英

相对路径在Angular2组件中不起作用

[英]Relative path is not working in Angular2 component

徽标未加载到组件的Angular 2中(导航栏)

导航栏组件文件:

import { Component, OnInit } from '@angular/core';
@Component({
  moduleId: module.id,
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {

  private website:string
  private websiteUrl:string
  constructor() {  
    this.website = 'Rakesh'
    this.websiteUrl = 'http://google.com'
   }
  ngOnInit() {
  }

}

我在模板文件中添加了一些html代码,徽标未加载

我的徽标是

<div class="navbar-header">
  <a class="navbar-brand" href="{{websiteUrl}}">
  *<img src="./logo/rakesh.png" class="img-responsive" alt="Image">*
  </a>
</div>

控制台moduleId should be a string in "NavbarComponent"输出moduleId should be a string in "NavbarComponent"

我的徽标路径:

navabar.component.ts
logo/
    rakesh.png

问题可能出在moduleId should be a string in "NavbarComponent"

由于Angular CLI现在使用Webpack,因此Webpack中的module.id是一个数字,而Angular需要一个字符串。 您应该做的是删除moduleId元数据。

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

@Component删除module.id 不再需要它,自Angular 2.0起,您可以在@NgModule找到它。

这就是webpack用户使用组件相对路径而不是module.id

Webpack:加载模板和样式

Webpack开发人员可以替代moduleId

他们可以在运行时加载模板和样式,方法是在引用组件相对 URL的模板和styles / styleUrls属性的开头添加./

 import { Component } from '@angular/core'; import '../../public/css/styles.css'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { } 

的WebPack会做require在幕后加载模板和样式。 在这里阅读更多。


如果您在打字稿中有编译错误, 答案可以为您提供帮助。

如果收到打字稿错误,只需在文件中声明变量。

 declare var module: { id: string; } @Component({ moduleId: module.id, ... }) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM