为什么不工作

时间:2017-09-14 15:55:43

标签: html angular typescript ecmascript-6

我希望在添加的名字和姓氏之间添加空格。但是当我运行代码时,它不会增加空间。我也试过添加tab sapce但是它没有正确渲染。字符集设置为utf-8,如附带的html

中所示

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>

3 个答案:

答案 0 :(得分:3)

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

相反,您应该将其保留为普通文本,并使用JS unicode escapes在代码中放置一个实际的不间断空格字符,而不是HTML转义符,例如使用\u00A0

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

答案 1 :(得分:1)

我假设这是Angular。

空格未打印,因为&nbsp;应该呈现为HTML。

<div [innerHTML]="title"></div>

Plunker

答案 2 :(得分:-1)

如果您只是添加这样的空格怎么办?

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

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

相关问题