如何在 Angular 中使用 ng-container 和 ngFor 渲染的项目之间添加常规(中断)空格以允许自动换行
使用 ngFor 在 ng-container 中渲染 html 锚标记时,标记之间的空格将被删除。结果是内容溢出了父容器。
我尝试在跨度内添加空格并使用  但这些在渲染时会被删除。
<ng-container *ngFor="let tag of tags">
<a [innerHTML]="tag"></a>
<span> </span>
</ng-container>
我发现的唯一方法是添加一个空格和另一个字符(例如 | 管道)并将其样式设置为透明,以便不可见。
<span class="wrap-hack"> |</span>
CSS
.wrap-hack {
color: transparent;
}
虽然这可行,但分隔空格允许自动换行,这有点麻烦。有“正确”的方法吗?
未经黑客攻击的结果
黑客攻击的结果
When rendering html anchor tags in an ng-container using ngFor, spaces between the tags are removed. The result is that the contents overflow the parent container.
I've tried adding a space inside a span and have used but these get removed on rendering.
<ng-container *ngFor="let tag of tags">
<a [innerHTML]="tag"></a>
<span> </span>
</ng-container>
The only way I've found is to add a space and another character (eg | pipe) and to style that as transparent so not visible.
<span class="wrap-hack"> |</span>
CSS
.wrap-hack {
color: transparent;
}
Although that works, the breaking space allows word wrapping, it's a bit of a hack. Is there a "correct" way?
Result without the hack
Result with hack
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是,默认情况下,Angular 会删除空格。为了防止这种情况,请添加preserveWhitespaces组件装饰器。
这个Stackblitz展示了preserveWhitespaces不需要的技巧。
Angular 参考
The issue is that by default, Angular is removing the whitespace. To prevent that, add the preserveWhitespaces component decorator.
This Stackblitz shows the hack which is not needed with preserveWhitespaces.
Angular Reference