如何在TypeScript中做换行?我在这里找不到解决办法。
实际上,我有一个方法显示10个数字,我想在每个数字上加一个换行符。
我已经尝试过n
,但不工作…
TS
export class AppComponent {
constructor() {}
public figure(): string {
let txt = '';
for (let i = 1; i < 11; i++) {
txt = txt + i + ' n ';
}
return txt;
}
}
HTML
<h1>Exercice 9 </h1>
<p> {{ figure() }} </p>
如果您想在浏览器控制台中打印它,那么n
应该足够了。如果你想在HTML中呈现它,那么我建议将数字存储在数组中,并通过Angular内置指令*ngFor
循环显示它:
public figure(): string {
let txt = [];
for (let i = 1; i < 11; i++) {
txt.push(i);
}
return txt;
}
<div *ngFor="let nr of figure()">
{{nr}}
</div>
另外,您应该将figure
结果存储在一个变量中,以避免冗余计算。
这里的问题不是typescript,而是你在HTML中呈现结果的事实。要让HTML显示换行符,需要<br/>
:
public figure(): string {
let txt = '';
for (let i = 1; i < 11; i++) {
txt = txt + i + '<br/>';
}
return txt;
}