为什么是   不工作

SON*_*TER 6 html typescript ecmascript-6 angular

我想在添加的名字和姓氏之间添加空格。但是当我运行代码时,它不会增加空间。我也尝试添加 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;
  }
}
Run Code Online (Sandbox Code Playgroud)
<!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>
Run Code Online (Sandbox Code Playgroud)

log*_*yth 9

在标题中使用 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}`;
Run Code Online (Sandbox Code Playgroud)


Mic*_*ael 5

我假设这是 Angular。

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

<div [innerHTML]="title"></div>
Run Code Online (Sandbox Code Playgroud)

普朗克