如何解决仅当 html 中存在字段时,Angular 5 联系字符串
我试图连接两个字段,但问题是在某些情况下第二个字段不存在。在下面的代码中,group.GroupDescription
字段不存在于某些整体中。仅当第二个字段 group.GroupDescription
存在时,有没有办法连接两个字段。
注意 - 我也尝试过安全导航操作符,但如果值不存在,它会显示 null。
感谢提前
<select
[(ngModel)]="selectedGroup"
class="form-control"
(ngModelChange)="onChange($event)"
>
<option [ngValue]="undefined" selected>Select</option>
<option *ngFor="let group of groups" [ngValue]="group">{{
group.GroupName.S + ' - ' + group.GroupDescription?.S
}}</option>
</select>
解决方法
<ng-container *ngIf="group.GroupDescription">
{{group.GroupName.S + ' - ' + group.GroupDescription.S}}
</ng-container>
<ng-container *ngIf="!group.GroupDescription">
{{group.GroupName.S}}
</ng-container>
,
一个快速而简单的解决方案可能是:
<select [(ngModel)]="selectedGroup" class="form-control" (ngModelChange)="onChange($event)">
<option [ngValue]="undefined" selected>Select</option>
<option *ngFor="let group of groups" [ngValue]="group">
{{
group.GroupName.S + (group.GroupDescription ? " - " + group.GroupDescription.S : '')
}}
</option>
</select>
但我建议您在代码中的其他位置预先构建字符串。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。