微语法`as`不适用于我自己的指令
Posted
技术标签:
【中文标题】微语法`as`不适用于我自己的指令【英文标题】:Micro syntax `as` not working with my own directive 【发布时间】:2021-11-06 02:52:26 【问题描述】:我想支持以下微语法:
foo$ | async as xyz
例子:
<p *appVar="foo$ | async as xyz">
Value is xyz !
</p>
该流被定义为
$foo = of('some value')
这是我的指令:
@Directive(
selector: '[appVar]'
)
export class VarDirective<T>
@Input() appVar: T;
constructor(
private templateRef: TemplateRef<T>,
private viewContainer: ViewContainerRef
)
ngOnInit(): void
this.viewContainer.createEmbeddedView(this.templateRef);
DEMO
现在,无论我做什么,xyz
变量始终是未定义的。
如果我创建一个上下文(在this 帖子中建议)
const context = $implicit: this.appVar ;
this.viewContainer.createEmbeddedView(this.templateRef, context);
DEMO
我得到相同的结果。有什么建议我在这里做错了吗?
【问题讨论】:
试试(foo$ | async) as xyz
不,同样的结果
【参考方案1】:
该表达式必须以与指令本身相同的名称在上下文中可用,在这种情况下为appVar
:
this.viewContainer.createEmbeddedView(this.templateRef,
$implicit: this.appVar,
appVar: this.appVar
);
Demo
将其与内置的ngIf
指令进行比较:
@Input()
set ngIf(condition: any)
this._context.$implicit = this._context.ngIf = condition;
this._updateView();
和TuiLetContext
:
get $implicit(): T
return this.internalDirectiveInstance.tuiLet;
get tuiLet(): T
return this.internalDirectiveInstance.tuiLet;
【讨论】:
【参考方案2】:我知道的唯一方法是使用“let”而不是“as”。有些人喜欢
@Input() appVar
ngOnInit(): void
this.viewContainer.createEmbeddedView(this.templateRef,
$implicit:this.appVar);
并使用
<p *appVar="foo$ | async;let data">
Value is data!
</p>
但我觉得这不是你要找的:(
【讨论】:
我很确定这应该是可能的。例如 TuiLet (article) 做同样的事情。 TuiLetsource code文件以上是关于微语法`as`不适用于我自己的指令的主要内容,如果未能解决你的问题,请参考以下文章