为什么   不起作用?

7

我希望在名字和姓氏之间加入空格,使用 添加空格时,但运行代码后并未添加空格。我还尝试添加制表符,但呈现效果不正确。可以在附加的HTML中看到字符集设置为UTF-8。

export class AppComponent implements OnInit {
  firstName: string;
  lastName: string;
  title: string;
  clicked: boolean;

  ngOnInit() {
    this.firstName = `John`;
    this.lastName = `Doe`;
  }

  printDetails(frstnm: HTMLInputElement, lstnm: HTMLInputElement, event: any): void {
    this.firstName = frstnm.value || this.firstName;
    this.lastName = lstnm.value || this.lastName;
    this.title = `First Name is: ${this.firstName}   Last Name is: ${this.lastName}`;
    event.preventDefault();
    this.clicked = true;
  }
  isVisible() {
    const classes = {
        display : this.clicked
    }
    return classes;
  }
}
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>MyApp</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>


Angular转义HTML实体。答案:https://dev59.com/RlwZ5IYBdhLWcg3wWvRY - Napas
8
如果你输入\u00A0,它有效吗? - loganfsmyth
@loganfsmyth 是的,它确实起作用了。为什么? - SONGSTER
1
@SONGSTER 因为 \u00A0 不是 HTML 实体。 - Michael
这是什么?你能否请提供更多详细信息? - SONGSTER
3个回答

11

在标题中使用HTML是没有意义的。如果你想使用&nbsp;,那么你必须将标题呈现为HTML才能正确呈现,但这也意味着如果用户在他们的名字中有任何HTML,那将会是一个问题。如果我用FirstName: "a <b>name</b>"注册您的网站,那么它将与空格一起呈现为粗体字。

相反,你应该将其保留为普通文本,并在你的代码中使用实际的不间断空格字符,使用JS Unicode转义字符而非HTML转义字符,例如使用\u00A0

this.title = `First Name is: ${this.firstName}\u00A0\u00A0\u00A0Last Name is: ${this.lastName}`;

5
我假设这是Angular。
空格没有打印出来,因为&nbsp;应该被解析为HTML。
<div [innerHTML]="title"></div>

Plunker


-2

如果你只是像这样添加空格呢?

this.title = `First Name is: ${this.firstName} Last Name is: ${this.lastName}`;

(注意...firstName}Last...之间的空格)


好的,我假设你是通过模板将文本传递给 innerHTML 属性(就像 Michael 提到的那样)。 - amal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接