2016-08-12 44 views
7

在我的angular 2(RC5)項目中,我有許多組件都可以正常工作,但是,我添加了一個子模塊,它的工作正常,除了其styleUrl屬性childComponent。如果我在tutorial(子模塊的根組件)中使用相同的url路徑,則應用樣式。如果我將完全相同的路徑添加到chapter(子模塊的子組件),那麼樣式不適用?styleUrls未被加載到angular2 ChildComponent(RC5)

在博客中沒有404通過,鉻的開發工具不會顯示chapter.css作爲源或網絡上存在的東西。

在這裏你可以看到組件害我的問題:

@Component({ 
    selector: 'chapter', 
    template: `<div [innerHTML]="content"></div>`, 
    styleUrls: ['app/tutorial/chapter/chapter.css'] 
}) 
export class chapterComponent implements OnInit, OnDestroy { 
    private sub: Subscription; 
    private content: string = ''; 

    constructor(private route: ActivatedRoute) { } 

    ngOnInit() { 
    this.sub = this.route.params.subscribe(params => { 
     var that = this; 
     var _url = './chapter/' + params['id'] + '.html'; 
     $.ajax({ 
     url: _url, 
     success: function (result) { 
      that.content = result; 
     } 
     }); 
    }); 
    } 
} 

chapter.css沒有被拾起......你可以看到我的項目文件在這裏:

 |-- error.html', 
     |-- index.html', 
     |-- app', 
      |-- app.component.ts', 
      |-- app.module.ts', 
      |-- app.routes.ts', 
      |-- main.ts', 
      |-- home', 
      | |-- home.component.ts', 
      | |-- home.css', 
      | |-- home.html', 
      |-- tutorial', 
       |-- tutorial.component.ts', 
       |-- tutorial.css', 
       |-- tutorial.html', 
       |-- tutorial.module.ts', 
       |-- tutorial.routes.ts', 
       |-- chapter', 
        |-- chapter.component.ts', 
        |-- chapter.css', 
        |-- chapter.html', 

只是爲什麼這個組件不起作用...我能看到的唯一區別是這個組件是一個子組件,所以也許這有所作爲?

更新:

正如關於答案的評論指出,使用教程組件./app/tutorial/chapter/chapter.css工作路徑,但完全相同的路徑不會在章部件的工作方式(這是一個子組件)。我還添加了ViewEncapsulation,但它沒有工作...

+0

難道你不覺得它應該是'/app/tutorial/chapter/chapter.css'(exact)嗎?或'。/ chapter/chapter.css' –

+0

或者試試./app/tutorial/chapter/chapter.css – Bean0341

+0

你是如何構建你的項目的?是webpack參與? – Jim

回答

11

嘗試增加 「封裝:ViewEncapsulation.None」 你父組件

import {ViewEncapsulation} from '@angular/core'; 

    @Component({ 
     encapsulation: ViewEncapsulation.None 
    }) 
+0

嗯,恐怕沒有什麼區別? –

+0

謝謝,爲我效勞 –

0

變化styleUrls: ['app/tutorial/chapter/chapter.css']styleUrls: ['./app/tutorial/chapter/chapter.css']

如果您想知道,../app/tutorial/chapter/chapter.css指定當前目錄。

+0

如果我在教程組件中使用該路徑,這些樣式就可以工作。如果我在章節組件中使用它,它不會...... –

1

http://blog.thoughtram.io/angular/2016/06/08/component-relative-paths-in-angular-2.html本文有幾種不同的方法來解決各種模塊加載器的相對路徑問題。這有助於我推理出現類似問題時的錯誤(儘管我使用的是webpack,但應該沒關係)。

關鍵的一課是在@Component裝飾器中設置moduleId:module.id!沒有moduleId設置,Angular 2會在相對於應用程序根目錄的路徑中查找我們的文件。

不要忘了你的tsconfig.json中的「module」:「commonjs」。

相關問題