angular - 使用 ngFor 创建不同的元素类型
问题描述
我正在遍历一个字符串数组(称为单词),并希望使用 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>
来处理 else 部分:
<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>
<ng-container>
如果您想了解更多信息,这里有一篇文章。
推荐阅读
- php - YAML 上的 PHP 查询运行器
- sql - Postgresql CTE 性能问题
- c# - asp.net core 3 服务器 websocket 支持
- php - 如何在不刷新的情况下使用href传递参数
- typescript - 选定的选项未滚动到 mat-select 中的视图中
- java - 无法使用发布工具或 URL 删除 solr 文档(使用查询)
- java - 何时将活动传递给另一个类会导致内存泄漏?
- c++ - Vulkan --- vkAcquireNextImageKHR 在使用某些队列族时抛出 std::out_of_range
- circleci - 找不到更改日志,因为没有给出版本代码 - 请指定:version_code
- r - 从 exec 目录执行脚本