我正在遍历一个字符串数组(称为单词),并希望使用 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
}
所有 span 和 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>
如果您需要更多信息。
关于angular - 使用 ngFor 创建不同的元素类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54774716/