如何在 Angular 中使用 ng-container 和 ngFor 渲染的项目之间添加常规(中断)空格以允许自动换行

发布于 2025-01-16 19:26:47 字数 881 浏览 6 评论 0原文

使用 ngFor 在 ng-container 中渲染 html 锚标记时,标记之间的空格将被删除。结果是内容溢出了父容器。

我尝试在跨度内添加空格并使用  但这些在渲染时会被删除。

<ng-container *ngFor="let tag of tags">
    <a [innerHTML]="tag"></a>
    <span>&#32;</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

enter image description here

Result with hack

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

难以启齿的温柔 2025-01-23 19:26:47

问题是,默认情况下,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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文