首页 > 解决方案 > 使用 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 元素) 的简单问题。这可能是一件简单的事情,但它逃脱了我。感谢任何帮助。

标签: angularangular-directive

解决方案


将你的*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>如果您想了解更多信息,这里有一篇文章。


推荐阅读