4

ERROR DOMException [InvalidCharacterError: "String contains an invalid character" code: 5 nsresult: 0x80530005 location: http://localhost:4200/vendor.bundle.js:67608]在尝试使用自定义属性指令编译 Angular 组件时得到。我的 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. 导致此类错误的原因是什么?2. 本案例中的错误是什么原因造成的?

谢谢

4

2 回答 2

4

问题是 addClass 中的空格,这是不允许的。

当我尝试这样做时,我得到了一个更具描述性的错误

错误 DOMException:无法在“DOMTokenList”上执行“添加”:提供的令牌(“ui leftAlign”)包含 HTML 空格字符,这些字符在令牌中无效。

您需要单独添加这两个类。

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

this附带说明一下,您应该从内部引用 AppComponent 。

export class AppComponent {
  public static SemanticUiBaseDir = '../../semantic/dist/';
  public getSemanticeUiBaseDir() : string{
    return this.SemanticUiBaseDir; // I changed AppComponent to this here
  }
  public constructor() {}
}
于 2017-07-14T22:54:06.100 回答
2

对我来说,导致此错误的原因是我的 HTML 中有一个无效字符。这是由于代码完成错误造成的,我想要非绑定的 HTML 属性,但我的代码完成选择了带方括号的绑定属性。我以为我删除了方括号,但我错过了尾随的一个。

因为 Angular 编译 HTML,你的模板被作为字符串读入,因此“字符串包含无效字符”。而且堆栈跟踪毫无价值,因为它被深深地捕获在 HTML 编译代码中,因此没有对我的文件的引用。

因此,如果您收到此错误并且堆栈跟踪不包含您的任何文件,但引用了名称中带有“HTML”的类,则您需要搜索您的 HTML。希望您的编辑器对 HTML 有一些错误突出显示,但如果没有,请开始注释掉您的 HTML 的大块,直到您确定它在哪个块中,然后从那里居中。我花了一点时间才找到那个不应该出现的狭窄的小方括号。

于 2020-09-27T15:19:51.177 回答