问题描述
我是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("-");
但是只是给我:
别让昨天占据了今天太多的时间。 ,威尔·罗杰斯(Will Rogers)
我正在寻找带打字稿的换行符,但是我所做的一切都没有用。我该怎么办?
解决方法
您正在使用TypeScript生成HTML页面的内容。因此,您的最终输出应该是HTML代码。要在HTML中换行,请使用<br>
标签。
您的TypeScript代码生成的输出应该是这样的:
<p>First Line.<br>Second Line</p>
Here是参考。
,可以通过在要中断引号的位置添加\ n来解决。
//By adding \n in the text you can Break the line. Happy Coding!
var test = "Hello\nWorld";
console.log(test);
,
如果您是自己设置引号,则可以从一开始就将作者与引号分开。
我不建议使用regexp
或split()
来将字符串分段成块,除非您非常清楚地知道将字符串拆分的位置,并且它永远不会失败或在错误的位置拆分。
示例
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
。