Vijayashankar Aruchamy
Vijayashankar Aruchamy

Reputation: 131

I have created a custom directive in angular for for-loop. getting a warning, 'Can't bind to 'appNgLoopOf' since it isn't a known property of 'p'

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

Answers (2)

Mahmmoud Kinawy
Mahmmoud Kinawy

Reputation: 891

Here I made custom directive just like the normal *ngFor and the code as the following:-
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

Marc
Marc

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

Related Questions