我有一个 Angular 组件,我在其中使用输入和列表来显示数组。
这里是组件的html
<div class="form-group col-md-6">
<label>{{ l('Tools') }}</label>
<div class="row mt-2">
<div class="col-8">
<input
#toolsInput="ngModel"
[(ngModel)]="tool"
class="form-control"
type="text"
name="tools"
maxlength="32"
/>
</div>
<div class="col-4">
<button
[disabled]="tool == null || tool == '' || tool.trim() == ''"
type="button"
class="btn btn-primary"
(click)="addItemToTools()"
>
<i class="fa fa-plus"></i>
</button>
</div>
</div>
<div class="row mt-2">
<div class="col-12">
<p-listbox
[readonly]="true"
[options]="tools"
[style]="{
width: '85%',
height: '200px',
overflow: 'auto',
'overflow-y': 'scroll'
}"
>
<ng-template let-tool let-i="index" pTemplate="item">
<div class="row" style="margin-right: 0px; margin-left: 0px;">
<div class="col-9">{{ tool.value }}</div>
<div class="col-1">
<button
type="button"
class="btn btn-primary"
(click)="removeTool(i)"
>
<i class="fa fa-times"></i>
</button>
</div>
</div>
</ng-template>
</p-listbox>
</div>
</div>
</div>
这是我的组件的 TS 代码(添加工具部分)
export class CreateJobComponent extends CreateEditModalComponentBase implements OnInit {
tools: SelectItem[] = [];
addItemToTools(): void {
this.tools.push({ value: this.tool, label: this.tool });
this.tool = null;
}
然后在保存方法中,我将其映射到 DTO 数组,如下所示 -
this.job.tools = this.tools.map(e => e.value);
但是如果数组为空,它映射空值。我该如何解决这个问题?
最佳答案
像这样尝试:
if(this.tools.length > 0)
this.job.tools = this.tools.map(e => e.value)
关于javascript - 空数组映射创建空值( Angular ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59068191/