如何在 Angular 6、7、8 [已解决] 中将图像放置在下拉选项中
如何在角度选择选项中插入图片
第一步:首先,安装 npm i ng-select2 npm 包。
step2 : 在你的 app.module.ts 中添加声明
import { NgSelect2Module } from 'ng-select2';
@NgModule({
imports: [
....,
NgSelect2Module
],
...
})
第三步:将代码添加到您的 html 文件中
<ng-select2 [data]="managersList" name="users"
formControlName="users" [options]="options">
</ng-select2>
第四步:添加代码ts文件
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>');
}
}
第 5 步:您的 Json 响应类似于,
userslis ==> [{
"id":"1",
"text":"murali",
"image":"--path--"
},
{
"id":"1",
"text":"murali_1",
"image":"--path--"
},
{
"id":"1",
"text":"murali_2",
"image":"--path--"
}]