html - 如何使用 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("-");
但这只是给我:
不要让昨天占据今天太多。, 威尔·罗杰斯
我用打字稿寻找换行符,但我所做的都没有奏效。我该怎么做?
解决方案
如果您自己设置引号,则可以从一开始就将作者与引号分开。
我不建议使用 a regexp
orsplit()
将字符串分块,除非您非常准确地知道在哪里拆分字符串并且它永远不会失败或在错误的位置拆分。
例子
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
在这个钩子中初始化。
推荐阅读
- html - 功能检测高级浏览器多选控件(例如 iOS/Android 选择元素)
- c# - 用于查找值的 Dynamics 365 插件
- php - 在每个函数上调用 mysql 链接或通过它们传递链接?
- stanford-nlp - 否定用户定义的“宏”的 TokensRegex 模式
- c - 有没有办法更好地路由流程?
- python - 我怎么知道引发异常的确切命令?
- java - 如何使用 javax.ws.rs 在请求正文中传递数据的 post 端点?
- amazon-web-services - 限制对云端分发背后的 s3 静态网站的访问
- python - 无服务器部署 Pip 失败 - 手动 Pip 成功
- google-cloud-vision - Image Properties detection-Dominant Colors 中使用了什么颜色空间?