我正在尝试创建一个允许我声明变量的指令(我以前一直在使用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-> TemplateRef)
并得到一个错误 Error: No provider for TemplateRef!
输入名称需要与选择器匹配才能通过这种方式分配
@Input()
set appVar(context: any) {
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句