Make any object iterable with the Typescript Iterable abstract class. The iterable class uses the standard Symbol.iterator symbol for iteration.
The easiest way is to install ts-iterable
as dependency
:
npm install ts-iterable --save
class Cart extends Iterable {
private articles: string[]
public constructor(...articles) {
super()
this.articles = articles
}
public valid(key): boolean {
return key < this.articles.length
}
public current(key): any {
return this.articles[key]
}
}
const cart = new Cart('flour', 'eggs', 'milk')
for (const article of cart) {
console.log(article)
}
// Displays:
// "flour"
// "eggs"
// "milk"
cart.component.ts
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html'
})
export class CartComponent {
public cart: Cart
public constructor() {
this.cart = new Cart('flour', 'eggs', 'milk')
}
cart.component.html
<h1>Your cart</h1>
<ul>
<li *ngFor="let article of cart">{{article}}</li>
</ul>
Code licensed under MIT License.