首页 > 解决方案 > 如何使用 TypeScript 换行

问题描述

我是 angular 新手,我正在尝试做一个随机报价生成器。我从教程中得到启发,到目前为止一切都很好,但我想在引用和作者之间添加一个换行符。

我有的:

不要让昨天占据今天太多。- 威尔罗杰斯

我想要的是:

不要让昨天占据今天太多。

威尔罗杰斯

到目前为止,我的 app.component.ts 中有这段代码:

quotes = [
'The Pessimist Sees Difficulty In Every Opportunity. The Optimist Sees The Opportunity In Every Opportunity',
"Don\'t Let Yesterday Take Up Too Much Of Today. -Will Rogers",
'You Learn More From Failure Than From Success. Don\'t Let It Stop You'
]
 getNewQuote() {
    const quoteText = document.querySelector('.quote-text');
    this.randomNumber = Math.floor(Math.random() * (this.quotes.length));
    quoteText.textContent = this.quotes[this.randomNumber];
    quoteText.textContent = this.quotes[this.randomNumber].split("-");
  }

我试过了

quoteText.textContent = this.quotes[this.randomNumber].split("-");

但这只是给我:

不要让昨天占据今天太多。, 威尔·罗杰斯

我用打字稿寻找换行符,但我所做的都没有奏效。我该怎么做?

标签: htmlangulartypescriptline-breaks

解决方案


如果您自己设置引号,则可以从一开始就将作者与引号分开。

我不建议使用 a regexporsplit()将字符串分块,除非您非常准确地知道在哪里拆分字符串并且它永远不会失败或在错误的位置拆分。

例子

Stackblitz:https ://stackblitz.com/edit/angular-ivy-ogfspj?file=src/app/app.component.ts

app.component.ts

import { Component, OnInit } from '@angular/core';

interface Quote {
  quote: string;
  author: string;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  public quote: Quote;
  private quotes: Quote[];

  ngOnInit(): void { 
    this.quotes = [
      {
        quote: 'The Pessimist Sees Difficulty In Every Opportunity. The Optimist Sees The Opportunity In Every Opportunity',
        author: 'unknown'
      }, {
        quote: 'Don\'t Let Yesterday Take Up Too Much Of Today', 
        author: 'Will Rogers'
      }, {
        quote: 'You Learn More From Failure Than From Success. Don\'t Let It Stop You',
        author: 'unknown'
      }
    ]

    this.random_quote()
  }

  private random_quote(): void {
    const index = Math.floor( Math.random() * this.quotes.length );
    this.quote = this.quotes[index];
  }

}

app.component.html

<blockquote>
  <i>{{quote.quote}}</i><br><br>
  - {{quote.author}}
</blockquote>

初学者外卖

从这个例子中对初学者的主要收获是:

  • 使用接口来定义Quote类型,这将更容易使用
  • 使用绑定属性{{}}
  • 大多数时候你想在ngOnInit生命周期钩子中初始化数据;您可能会在某个时候重构此代码以从服务中获取报价。然后你需要quote在这个钩子中初始化。

推荐阅读