I am curious about the role of the context
parameter in the createEmbeddedView()
method within Angular. The official Angular documentation does not provide clear information on this aspect.
For instance, I came across a piece of code where the developer implemented an iterator structural directive.
import {
Directive, ViewContainerRef, TemplateRef, Input, SimpleChange
} from "@angular/core";
@Directive({
selector: "[paForOf]"
})
export class PaIteratorDirective {
constructor(private container: ViewContainerRef, private template: TemplateRef<Object>) {
}
@Input("paForOf") dataSource: any;
ngOnInit() {
this.container.clear();
for (let i = 0; i < this.dataSource.length; i++) {
this.container.createEmbeddedView(this.template, new PaIteratorContext(this.dataSource[i]));
}
}
}
class PaIteratorContext {
constructor(public $implicit: any) { }
}
The implementation involves triggering the functionality on a checkbox checked event within the template:
<div class="checkbox">
<label><input type="checkbox" [(ngModel)]="showTable" />Show Table</label>
</div>
<table *paIf="showTable" class="table table-sm table-bordered table-striped">
<tr>
<th></th>
<th>Name</th>
<th>Category</th>
<th>Price</th>
</tr>
<template [paForOf]="getProducts()" let-item>
<tr>
<td colspan="4">{{item.name}}</td>
</tr>
</template>
</table>
I am particularly interested in the following line of code:
this.container.createEmbeddedView(this.template, new PaIteratorContext(this.dataSource[i]));
Why is it necessary to instantiate an object of the PaIteratorContext() class? Can't we simply pass this.dataSource[i]
directly?
Your insights would be greatly appreciated!