How to place image on dropdown options in Angular 6,7,8 [Solved]
how to insert image in select options in angular
step1: Firts, Install npm i ng-select2 npm package.
step2 : Add declaration to your app.module.ts
import { NgSelect2Module } from 'ng-select2';
@NgModule({
imports: [
....,
NgSelect2Module
],
...
})
step3: Add code to your html file
<ng-select2 [data]="managersList" name="users"
formControlName="users" [options]="options">
</ng-select2>
step4: add code ts file
export class dropDownImage implements OnInit {
public exampleData: Array<Select2OptionData>;
public options: Options;
constructor(private service: DataService) { }
ngOnInit() {
this.exampleData = this.service.getTemplateList();
this.options = {
width: '300',
templateResult: this.templateResult,
templateSelection: this.templateSelection
};
}
// function for result template
public templateResult = (state: Select2OptionData): JQuery | string => {
if (!state.id) {
return state.text;
}
let image = '<span class="image"></span>';
if (state.additional.image) {
image = '<span class="image"><img src="' + state.additional.image + '"</span>';
}
return jQuery('<span><b>' + state.additional.winner + '.</b> ' + image + ' ' + state.text + '</span>');
}
// function for selection template
public templateSelection = (state: Select2OptionData): JQuery | string => {
if (!state.id) {
return state.text;
}
return jQuery('<span><b>' + state.additional.winner + '.</b> ' + state.text + '</span>');
}
}
step 5 : your Json responce like ,
userslis ==> [{
"id":"1",
"text":"murali",
"image":"--path--"
},
{
"id":"1",
"text":"murali_1",
"image":"--path--"
},
{
"id":"1",
"text":"murali_2",
"image":"--path--"
}]