【问题标题】:why is   not working为什么不工作
【发布时间】:2018-02-23 16:52:12
【问题描述】:

我想在名字和姓氏之间添加空格。但是当我运行代码时,它不会增加空间。我也尝试添加选项卡空间,但它没有正确渲染。字符集设置为 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>

【问题讨论】:

标签: html angular typescript ecmascript-6


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    我假设这是 Angular。

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

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

    Plunker

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

      • 好的,我假设您将文本传递给模板中的innerHTML 属性(就像@Michael 提到的那样)。
      猜你喜欢
      • 2016-11-19
      • 1970-01-01
      • 2015-06-15
      • 2013-06-01
      • 2011-09-29
      • 2014-05-16
      • 2011-01-21
      • 2016-03-11
      • 2011-04-04
      相关资源
      最近更新 更多