In Angular @ng-select, How can we always show a template even if no option is selected?
If an option is selected, I can use ng-multi-label-tmp. If No option is selected, ng-multi-label-tmp is not rendering. Placeholder is rendering. I need to put a template instead of placeholder (which should be displayed in both situations 1. No option is selected, and 2. Some options are selected).
<ng-select
[items]="users$ | async"
[multiple]="true"
bindLabel="name"
bindValue="email"
[(ngModel)]="selectedUsers">
<ng-template ng-multi-label-tmp let-items="items" > <div > <span> <!--Some icons and labels here. This part dissapears when selectedUsers.length is zero. Even though it is outside the ngFor--> </span> </div> <div *ngFor="let item of items"> <span> {{item.name}}</span> <span (click)="clear(item)">×</span> </div>
</ng-template> 3 1 Answer
The template will only render if items are present. As far as I know (and after checking the source code of the library), this behavior cannot be changed without modifying the library. I would suggest opening an issue to discuss this feature; it should be easy to implement.
There is a possible workaround, but it's not pretty.
You can add a dummy item to your selectedUsers collection to ensure that it is never empty. This item must be identifiable so that you can hide it.
component:
selectedUsers = ['hidden'];template:
<div *ngFor="let item of items"> <ng-container *ngIf="item.email !== 'hidden'"> <span> {{item.name}}</span> <span (click)="clear(item)"></span> </ng-container>
</div>As this dummy item will be removed when all selected items are cleared, you have to disable the clear all functionality on ng-select: [clearable]="false", or only enable it when more than one item is selected [clearable]="selectedUsers.length > 1". In the later case, you will have to add your dummy item again after clearing.