我正在遍历一个字符串数组(称为单词),并希望使用Angular / Typescript为每个单词创建span元素,并为行尾字符(\ n)创建br元素。我有ngFor指令工作:
<div id = documentContents *ngIf="showDocument">
<span *ngFor="let word of words" >
{{word}}
</span>
</div>
它目前创建了所有内容的跨度,甚至是数组中的br元素。注意:在解析文档时,我会在行尾字符中创建br元素。没有结合这个解决方案,似乎是一个好主意。从逻辑上讲,我想做的事情如下:
if(word != "<br/>") {
<span> {{word}} </span>
}
else {
create a <br/> element
}
将所有跨度和br元素附加到包含div并保持原始源格式(尽可能多)
但我不确定如何实现ngIf部分。我已经尝试将ngFor指令放在包含div元素(docContents)上,但随后它生成了div元素副跨(预期)。我用javascript编写了类似的东西,只是document.append(span或br元素)的简单问题。这可能是一件简单的事情,但它逃脱了我。感谢任何帮助。
将*ngFor
放在<ng-container>
上,它不会在运行时向DOM添加额外的元素。
并将内部*ngIf
与<ng-template>
的模板引用一起处理其他部分:
<div id = documentContents *ngIf="showDocument">
<ng-container *ngFor="let word of words" >
<span *ngIf="word !== '\n'; else br">{{ word }}</span>
<ng-template #br><br /></ng-template>
</ng-container>
</div>
Here is an article在<ng-container>
,如果你想了解更多信息。
只是@ jo_va的答案的替代品,IMO稍微容易阅读:
<div id="documentContents" *ngIf="showDocument">
<ng-container *ngFor="let word of words">
<span *ngIf="word !== '\n'">{{word}}</span>
<br *ngIf="word === '\n'">
</ng-container>
</div>
如果单词不是换行符,则只显示一个跨度,否则显示<br>
。
唯一的缺点是重复这个条件,可以通过在组件上添加一个简单的isNewline()
方法并使用!isNewLine()
/ isNewLine()
来修复。
但是:Kua zxsw指出