【问题标题】:New Line '\n' is not working in Typescript新行“\ n”在打字稿中不起作用
【发布时间】:2017-11-28 08:30:54
【问题描述】:

我正在 typescript 组件中创建一个列表项,该列表项将显示在 UI 中。列表项应显示在单独的行中。所以我添加了新行 char \n 如下。但列表项仍然显示在同一行。下面是代码。知道为什么它不起作用吗?

打字稿代码:

@Output() excludeDisplay: any = '';
@Output() includeDisplay: any = '';
includeValues: any = '';
excludeValues: any = '';

this.includeValues += this.merId + ',' + this.explodeStatus + '\n';
console.log("include values are "+ this.includeValues);
this.excludeValues += this.merId + ',' + this.explodeStatus + '\n';
console.log("exclude values are "+ this.excludeValues);
this.includeDisplay = this.includeValues;
this.excludeDisplay = this.excludeValues;

HTML代码:

<ul id="excludedUl" required>{{ excludeDisplay }}</ul>
<ul id="includedUl" required>{{ includeDisplay }}</ul>

CSS 代码:

#includedUl {
  float: right;
  width: 33%;
}

#excludedUl {
  float: right;
  width: 33%;
}

【问题讨论】:

标签: css html typescript


【解决方案1】:

需要使用固定宽度:

 <div style="width: 500px;white-space: pre-line">{{property}}</div>

在 typescript 中使用 '\n' 添加新行。

【讨论】:

    【解决方案2】:

    \n不会在 html 中造成换行符。
    您需要使用 &lt;br/> 或将文本包装在块元素中。

    this.includeValues += this.merId + ',' + this.explodeStatus + '<br/>';
    this.excludeValues += this.merId + ',' + this.explodeStatus + '<br/>';
    

    或者

    this.includeValues += '<div>' + this.merId + ',' + this.explodeStatus + '</div>';
    this.excludeValues += '<div>' + this.merId + ',' + this.explodeStatus + '</div>';
    

    【讨论】:

    • @VladimirDespotovic 所以你决定投反对票。好的。您可能正在做一些不同的事情,因为&lt;br/&gt; 是在 html 中执行此操作的方式。
    • 感谢您的回答。我将删除反对票。但是,n 对我不起作用,br.......
    • mje 发生的事情是,在网页中,
      只是这样显示:) 即
      ......angular 对其进行了预格式化。我正在寻找将 br 显示为 br .....
    • @VladimirDespotovic 那么,这不适合您。 \n 不应该工作,所以好的,至于 `
      ',还有其他线程,即:stackoverflow.com/questions/14963444/…
    【解决方案3】:

    如果信息只在 HTML 中显示,您可以使用 CSS 属性 white-space。对于仅破坏 '\n' 字符,这应该可以工作white-space: pre-line;,如提到的here 和文档检查MDN

    【讨论】:

      【解决方案4】:

      如果您仍然需要包含\n 的原始文本来做其他事情,您可以随时调用Str.replace 方法,将所有\n 更改为&lt;br/&gt;,这样模板就可以按预期工作。你可以这样做:

      this.includeDisplay = this.includeValues.replace(/\n/g, '<br />');
      

      您可以参考MDN docs

      【讨论】:

        猜你喜欢
        • 2016-06-16
        • 2018-12-25
        • 1970-01-01
        • 2018-11-23
        • 2023-04-07
        • 2020-03-18
        • 1970-01-01
        • 2017-02-20
        相关资源
        最近更新 更多