2017-07-14 66 views
1

嘗試使用自定義屬性指令編譯Angular組件時出現ERROR DOMException [InvalidCharacterError: "String contains an invalid character" code: 5 nsresult: 0x80530005 location: http://localhost:4200/vendor.bundle.js:67608]。我對AppComponent,指令和基礎模板代碼下面給出:無效字符錯誤角度

leftAlign.directive.ts

import { 
    Directive, 
    HostListener, 
    HostBinding, 
    Input, 
    Output, 
    ElementRef, 
    Renderer2 // for host class binding 
} from '@angular/core'; 

@Directive({ 
    selector: '[leftAlign]' 
}) 
export class LeftAlignDirective { 

    public constructor(
    private el: ElementRef, 
    private renderer: Renderer2 
) { 
    this.renderer.addClass(this.el.nativeElement, 'ui leftAlign'); 
    } 
} 

app.component.ts

import { Component } from '@angular/core'; 
import { LeftAlignDirective } from './Directives/left-align.directive'; 


@Component({ 
    selector: `app-root`, 
    templateUrl: './app.component.html' 
}) 
export class AppComponent { 
    public static SemanticUiBaseDir = '../../semantic/dist/'; 
    public getSemanticeUiBaseDir() : string{ 
    return AppComponent.SemanticUiBaseDir; 
    } 
    public constructor() {} 
} 

app.component.html

!-- 
    @ semantic-ui.min.css 
--> 
<link rel="stylesheet" type="text/css" href="/home/zerocool/km-live/FrontEndComponent/semantic/dist/semantic.css"> 

<!-- 
    @ @semantic.min.js 
--> 
<script src="./home/zerocool/km-live/FrontEndComponent/semantic/semantic.js"></script> 

<p leftAlign>This should be aligned left!</p> 

我有興趣瞭解以下內容: 1.什麼導致s uch錯誤? 2.在這種情況下導致錯誤的原因是什麼?

謝謝

回答

0

問題是addClass中的空間,它是不允許的。

我得到了更多的描述性的錯誤,當我嘗試這樣做

錯誤拋出:DOMException:未能執行「添加」上「DOMTokenList」:所提供的令牌(「UI leftAlign」)包含HTML空格字符,這在令牌中是無效的。

您需要分別添加兩個類。

this.renderer.addClass(this.el.nativeElement, 'ui'); 
this.renderer.addClass(this.el.nativeElement, 'leftAlign'); 

在一個側面說明,你應該參考AppComponent作爲this從內部本身。

export class AppComponent { 
    public static SemanticUiBaseDir = '../../semantic/dist/'; 
    public getSemanticeUiBaseDir() : string{ 
    return this.SemanticUiBaseDir; // I changed AppComponent to this here 
    } 
    public constructor() {} 
} 
+0

我試過解決方案,它工作。還有一個問題:是否允許使用'this'調用靜態方法或調用靜態屬性?我的理解是靜態成員應該使用類名稱而不是「this」來引用。 –

+0

是的,這是正確的,你不這樣引用靜態成員,我錯過了你使它靜態。 – efarley