Reputation: 131
my-for.directive.ts
@Directive({
selector: '[appMyFor]'
})
export class MyForDirective implements OnInit, OnChanges {
@Input() appMyForOf: Array<any>;
constructor(private temRef: TemplateRef<any>, private viewRef: ViewContainerRef) { }
ngOnChanges(changes: import("@angular/core").SimpleChanges): void {
for (const input of this.appMyForOf) {
this.viewRef.createEmbeddedView(this.temRef, {
$implicit: input,
index: this.appMyForOf.indexOf(input),
});
}
}
ngOnInit(): void {
}
}
My view looks like:
d-test2.component.html
<p *appMyFor="let nr of numbers">
{{ nr }}
</p>
component looks like:
d-test2.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-d-test2',
templateUrl: './d-test2.component.html',
styleUrls: ['./d-test2.component.css']
})
export class DTest2Component implements OnInit {
constructor() { }
numbers = [1, 2, 3];
ngOnInit(): void {
}
}
so the problem here is paragraph element in d-test2.component.html not rendered in the browser. seeing a warning in the browser console.
Upvotes: 2
Views: 833
Reputation: 891
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appTimes]',
})
export class TimesDirective {
constructor(
private viewContainer: ViewContainerRef,
private templateRef: TemplateRef<any>
) {}
@Input('appTimes') set render(times: number) {
this.viewContainer.clear();
for (let i = 0; i < times; i++) {
this.viewContainer.createEmbeddedView(this.templateRef, {});
}
}
}
Upvotes: 1
Reputation: 1896
You must declare your directive in the corresponding module with
@NgModule({
declarations: [MyForDirective],
exports: [MyForDirective] ...
If you want to use it outside this module, you have to export it.
Your selector ([appMyFor]) should also be your input decorator:
@Input() appMyFor: Array<any>;
Upvotes: 1