[英]Relative path is not working in Angular2 component
Logo not loading in Angular 2 in a component (Navbar) 徽标未加载到组件的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() {
}
}
i add some html code in template file and the logo not loading 我在模板文件中添加了一些html代码,徽标未加载
<div class="navbar-header">
<a class="navbar-brand" href="{{websiteUrl}}">
*<img src="./logo/rakesh.png" class="img-responsive" alt="Image">*
</a>
</div>
Output in console moduleId should be a string in "NavbarComponent"
. 控制台moduleId should be a string in "NavbarComponent"
输出moduleId should be a string in "NavbarComponent"
。
navabar.component.ts
logo/
rakesh.png
Problem maybe comes from moduleId should be a string in "NavbarComponent"
. 问题可能出在moduleId should be a string in "NavbarComponent"
。
As Angular CLI now use Webpack, module.id in Webpack is a number, while Angular expects a string. 由于Angular CLI现在使用Webpack,因此Webpack中的module.id是一个数字,而Angular需要一个字符串。 What you should do is remove the moduleId
metadata. 您应该做的是删除moduleId
元数据。
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
Remove module.id
from @Component
. 从@Component
删除module.id
。 It doesn't need anymore, you can find it in @NgModule
since Angular 2.0. 不再需要它,自Angular 2.0起,您可以在@NgModule
找到它。
This is how webpack users use component relative paths instead of module.id
. 这就是webpack用户使用组件相对路径而不是module.id
。
Webpack: load templates and styles Webpack:加载模板和样式
Webpack developers have an alternative to
moduleId
. Webpack开发人员可以替代moduleId
。They can load templates and styles at runtime by adding
./
at the beginning of the template andstyles / styleUrls
properties that reference component-relative URLS. 他们可以在运行时加载模板和样式,方法是在引用组件相对 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 will do a
require
behind the scenes to load the templates and styles. 的WebPack会做require
在幕后加载模板和样式。 Read more here . 在这里阅读更多。
This answer can help you if you have compilation errors in typescript. 如果您在打字稿中有编译错误, 此答案可以为您提供帮助。
If you get typescript error, just declare the variable in your file. 如果收到打字稿错误,只需在文件中声明变量。
declare var module: { id: string; } @Component({ moduleId: module.id, ... })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.