我正在尝试创建一个指令,允许我声明变量(我以前一直使用 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);
}
}
Run Code Online (Sandbox Code Playgroud)
我已经声明并从我的共享模块导出:
@NgModule({
imports: [
CommonModule,
RouterModule,
FormsModule,
ReactiveFormsModule
],
declarations: [
...
VarDirective
],
exports: [
...
VarDirective
]
})
export class SharedModule {}
Run Code Online (Sandbox Code Playgroud)
哪个被导入到我正在尝试使用的模块中。但是,当我尝试:
<div *appVar="'test' as dataState">
Run Code Online (Sandbox Code Playgroud)
我收到错误Can't bind to 'appVar' since it isn't a known property of 'div'.我看到的所有其他答案似乎都是指令不在范围内的问题(从模块等导出)。但是,我知道该appVar指令在范围内,因为如果我删除星号,它不会立即出现问题:
<div appVar="'test' as dataState">
Run Code Online (Sandbox Code Playgroud)
但是,如果没有星星,我在加载组件时会遇到这个问题:
Angular2 没有 TemplateRef 的提供者!(NgIf ->TemplateRef)
并得到一个错误 Error: No provider for TemplateRef!