我试图创建一个允许我声明变量的指令(我以前一直使用ngIf来做这个,但我不喜欢这样做)。基于第二个答案:How to declare a variable in a template in 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 No provider for TemplateRef! (NgIf ->TemplateRef)
并收到错误Error: No provider for TemplateRef!
答案 0 :(得分:2)
输入名称需要匹配选择器以便能够以这种方式分配
@Input()
set appVar(context: any) {