自定义指令:无法绑定到指令,因为它不是元素的已知属性



我正在尝试创建一个指令,该指令将使我声明变量(我以前一直在使用NGIF来执行此操作,但我不喜欢这样做)。基于这里的第二个答案:如何在Angular2中的模板中声明变量

我有指令

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);
  }
}

我已声明并从共享模块中导出:

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

将导入到我要使用的模块中。但是,当我尝试时:

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

我正在收到错误Can't bind to 'appVar' since it isn't a known property of 'div'.我所看到的所有其他答案似乎是一个问题,即指令不在范围内(从模块等导出)。但是,我知道appVar指令处于范围,因为如果我删除星星,则没有直接的问题:

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

但是,如果没有恒星,我在加载组件时面对这个问题:

angular2没有templateref的提供商!(ngif - &gt; templateref)

并获得错误Error: No provider for TemplateRef!

输入名称需要与选择器匹配以使其分配方式

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

最新更新