Joe
Joe

Reputation: 7004

Custom Directive: Can't bind to directive since it isn't a known property of element

I'm trying to create a directive that will allow me to declare variables (I've previously been using ngIf to do this, but I dislike doing that). Based off the second answer here: How to declare a variable in a template in Angular2

I have a directive

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[appVar]',
})
export class VarDirective {
  @Input()
  set ngVar(context: any) {
    (this.context as any).$implicit = (this.context as any).ngVar = context;
    this.updateView();
  }

  context = {};

  constructor(private vcRef: ViewContainerRef, private templateRef: TemplateRef<any>) { }

  updateView() {
    this.vcRef.clear();
    this.vcRef.createEmbeddedView(this.templateRef, this.context);
  }
}

I have it declared and exported from my shared module:

@NgModule({
  imports: [
    CommonModule,
    RouterModule,
    FormsModule,
    ReactiveFormsModule
  ],
  declarations: [
    ...
    VarDirective
  ],
  exports: [
    ...
    VarDirective
  ]
})
export class SharedModule {}

Which is imported into the module I'm trying to use it. However when I try:

<div *appVar="'test' as dataState">

I'm getting the error Can't bind to 'appVar' since it isn't a known property of 'div'. All the other answers I've seen seem to be a problem with the directive not being in scope (exported from modules etc). However, I know that the appVar directive is in scope, because if I remove the star it has no immediate problem:

<div appVar="'test' as dataState">

However, without the star I face this problem when the component is loaded:

Angular2 No provider for TemplateRef! (NgIf ->TemplateRef)

And get an error Error: No provider for TemplateRef!

Upvotes: 3

Views: 6380

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657731

The input name needs to match the selector to be able to assign this way

@Input()
set appVar(context: any) {

Upvotes: 13

Related Questions