Skip to content

Instantly share code, notes, and snippets.

@ierhalim
Last active August 1, 2021 14:15
Show Gist options
  • Save ierhalim/0d68b9707ab916228b03a107b72ac051 to your computer and use it in GitHub Desktop.
Save ierhalim/0d68b9707ab916228b03a107b72ac051 to your computer and use it in GitHub Desktop.
Basic NgTemplate
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<app-my-list
[data]="employeeList"
[itemTemplate]="myTemplate"
[emptyTemplate]="noDataTemplate"
>
<!--Content of the list defined here but but will be bind in app-my-list -->
<ng-template #myTemplate let-employee="item">
<img [src]="employee.image" width="200" height="200"> {{employee.name}} {{employee.lastName}}
</ng-template>
<ng-template #noDataTemplate>
<div class="warning">No records found.</div>
</ng-template>
</app-my-list>
`,
})
export class AppComponent implements OnInit {
employeeList: Array<unknown>;
ngOnInit() {
// Data created with: https://www.mockaroo.com/
this.employeeList = [
{ name: 'Molly', lastName: 'Passler', image: 'http://dummyimage.com/132x100.png/ff4444/ffffff' },
{ name: 'Elisabeth', lastName: 'Bastow', image: 'http://dummyimage.com/243x100.png/dddddd/000000' },
{ name: 'Faunie', lastName: 'Lamers', image: 'http://dummyimage.com/119x100.png/5fa2dd/ffffff' },
{ name: 'Kendricks', lastName: 'Rackley', image: 'http://dummyimage.com/178x100.png/5fa2dd/ffffff' },
{ name: 'Cassy', lastName: 'Golland', image: 'http://dummyimage.com/132x100.png/ff4444/ffffff' }
];
}
}
import { Component, Input, TemplateRef } from '@angular/core';
@Component({
selector: 'app-my-list',
template: `
<div class="my-list">
<ng-container *ngIf="!!data && data.length > 0 else emptyTemplate">
<div class="list-item" *ngFor="let item of data">
<ng-container *ngTemplateOutlet="itemTemplate;context:{item:item}"></ng-container>
</div>
</ng-container>
</div>
`,
})
export class MyListComponent {
@Input()
data: Array<unknown>;
@Input()
itemTemplate: TemplateRef<unknown>;
@Input()
emptyTemplate: TemplateRef<unknown>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment