繁体   English   中英

如何在 Angular 组件的 HTML 模板端使用联合类型

[英]How to use union types in the HTML template side of an Angular component

在 Angular 组件的 HTML 部分中,我想在不同条件下显示复选框或图标。 使用许可 model { checked?: boolean; icon?: string } { checked?: boolean; icon?: string } ,我可以这样做:

<input type="checkbox" [(ngModel)]="item.checked" *ngIf="!item.icon">
<i class="{{item.icon}}" *ngIf="item.icon">

此 model 启用无效状态,例如同时具有checkedicon 拥有更强的 model 可以依赖联合类型: { checked: boolean } | { icon: string } { checked: boolean } | { icon: string } 但它在 HTML 中不再起作用,因为checkedicon在“联合类型”级别可用,但仅在左侧或右侧情况下可用。

有没有办法在一些经过调整的 HTML 模板中使用这个 model ?

有点晚了,但我现在有类似的问题。 如果找到了解决方案,但它不是很优雅。 我希望有更好的东西......您可以将您的项目包装在 $any() 运算符中,如下所示:

<input type="checkbox" [(ngModel)]="$any(item).checked" *ngIf="!item.icon">
<i class="{{$any(item).icon}}" *ngIf="item.icon">

那应该行得通。

这不是我期望的解决方案,而是一个调整

我们可以使用联合类型键入我们的item ,并且仍然在 HTML 模板中使用它,但通过tweak function 只需调整类型以使 2 个内部类型相互兼容。 因此,我们的想法是在 HTML 模板中使用“调整项目”,并且仍然在 TypeScript 代码的 rest 中使用常规项目。

这是 TypeScript 中的演示代码,其中props模拟了 HTML 模板中的用法:

type Item =
  | { checked: boolean }
  | { icon: string };

const items: Item[] = [{ checked: true }, { icon: 'checked' }];

const propsKo = items.map(x => ({ checked: x.checked, icon: x.icon }));
//                                           ~~~~~~~          ~~~~
// 💥 Property 'xxx' (icon/checked) does not exist on type 'Item'


// 💡 Tweak
type ItemTweaked =
  | { checked: boolean; icon: never }
  | { icon: string; checked: never };

const tweak = (item: Item) => item as ItemTweaked;

const propsOk = items.map(tweak).map(x => ({ checked: x.checked, icon: x.icon }));
//                        ^^^^^

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM