Dynamic listview by loading ajax html content in EJ2 JavaScript Listview control
8 Aug 20233 minutes to read
We can set external HTML
page content as template
for our ListView
control by making use of AJAX
call.
let template: string;
let ajax: Ajax = new Ajax('./template.html', 'GET', false);
ajax.onSuccess = (e: string)=>{
template = e;
}
ajax.send();
In the below sample, we have rendered smartphone settings template from external HTML
file.
var data = [
{ name: 'Network & Internet', id: '0', description: 'Wi-Fi, mobile, data usage, hotspot' },
{ name: 'Connected devices', id: '1', description: 'Bluetooth, cast, NFC' },
{ name: 'Battery', id: '2', description: '18% -4h 12m left' },
{ name: 'Display', id: '3', description: 'Wallpaper, sleep, font size' },
{ name: 'Sound', id: '4', description: 'Volume, vibration, Do Not Disturb' },
{ name: 'Storage', id: '5', description: '52% used - 15.48 GB free' }
];
var template;
var ajax = new ej.base.Ajax('./template.html', 'GET', true);
ajax.send().then();
ajax.onSuccess = function(e){
template = e;
listfunction();
}
function listfunction(){
listViewInstance.template = template;
listViewInstance.refresh();
}
ajax.onFailure = function(reason){
console.log(reason);
}
var listViewInstance = new ej.lists.ListView({
dataSource: data,
headerTitle: 'Settings',
showHeader: true,
template: template,
fields: {text:'name', id: 'id'}
});
listViewInstance.appendTo('#element');
<html><head><script src="https://cdn.syncfusion.com/ej2/23.2.4/dist/ej2.min.js" type="text/javascript"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head><body><div class="settings-container">
<div class="name">${name}</div>
<div class="description">${description}</div>
</div><script>
var ele = document.getElementById('container');
if(ele) {
ele.style.visibility = "visible";
}
</script>
<script src="index.js" type="text/javascript"></script>
</body></html>