【问题标题】:Micro syntax `as` not working with my own directive微语法`as`不适用于我自己的指令
【发布时间】: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
  • 不,同样的结果

标签: angular angular-structural-directive


【解决方案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文件
    猜你喜欢
    • 1970-01-01
    • 2019-07-23
    • 2020-01-01
    • 2013-08-13
    • 2019-01-22
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多