簡體   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