如何向ng-select下拉列表中添加一个额外的项,例如Create New in the following image
:
这是我当前拥有的代码:
<ng-select
[multiple]="true"
[hideSelected]="true"
[items]="robots"
formControlName="RobotGUID"
bindLabel="Name"
bindValue="GUID"
>
<ng-template ng-label-tmp let-item="item" let-clear="clear">
<ng-container *ngIf="item.GUID">
<span class="ng-value-icon left" (click)="onRobotEditClick($event, item.GUID)" aria-hidden="true">
<i class="fas fa-edit btn-focus"></i>
</span>
<span class="ng-value-label">{{item.Name}}</span>
<span class="ng-value-icon right" (click)="clear(item)" aria-hidden="true">×</span>
</ng-container>
</ng-template>
</ng-select>
我尝试使用<ng-option>
,但该项目未出现在下拉菜单中。
如何在模板中添加额外的项目?
答案 0 :(得分:7)
您可以使用 [addTag]
和 addTagText
。
[addTag]
:允许创建自定义选项。addTagText
:使用标记时设置自定义文本。app.component.html :
<ng-select [items]="cities"
bindLabel="name"
placeholder="Select city"
[(ngModel)]="selectedCity"
addTagText="Create New"
[addTag]="CreateNew">
</ng-select>
app.component.ts :
export class AppComponent {
cities = [
{id: 1, name: 'City1'},
{id: 2, name: 'City2'},
{id: 3, name: 'City3'},
{id: 4, name: 'City4'},
{id: 5, name: 'City5'}
];
CreateNew(city){
alert("Create New Clicked : "+city)
}
}
图片:
2.
答案 1 :(得分:6)
您可以使用ng-footer-tmp
在选择框中添加其他项目。
尝试这样:
.html
<ng-select [items]="cities"
bindLabel="name"
placeholder="Select city"
[(ngModel)]="selectedCity">
<ng-template ng-footer-tmp>
<p class="create-new" (click)="CreateNew()">Create New </p>
</ng-template>
</ng-select>
.style.css
.create-new {
cursor: pointer;
padding-top:5px;
padding-bottom:10px
}
.ng-dropdown-footer{
border-top:unset !important;
padding: 0px 10px !important;
}
.ng-dropdown-footer:hover {
background-color: #f5faff;
}