【问题标题】:Angular structural directive context template type checkingAngular 结构指令上下文模板类型检查
【发布时间】:2020-05-24 19:14:35
【问题描述】:

我似乎无法使角度模板自动完成工作,谁能帮助我了解我错过了什么或做错了什么?

<div *ngVar="ok as xd">
    <!-- xd is not giving any autocomplete / typecheck, hover giving "any" type -->
    {{ xd.item }}
</div>

我几乎继续阅读 ngIf 和异步管道源代码,试图了解发生了什么,并制定了这个简单的指令,只是为了方便我的异步订阅生活(这对 ngIf 来说有点痛苦。
没有类型安全同样很痛苦 x)

type NgVarContext<T> = { ngVar: T; $implicit: undefined };

@Directive({
    selector: "[ngVar]",
})
export class NgVar<T> {
    context: NgVarContext<T> = { ngVar: undefined, $implicit: undefined };
    _subscription: Subscription;

    constructor(
        private cdr: ChangeDetectorRef,
        template: TemplateRef<NgVarContext<T>>,
        viewContainer: ViewContainerRef
    ) {
        viewContainer.createEmbeddedView(template, this.context);
    }

    @Input()
    set ngVar(input: Observable<T>) {
        if (this._subscription) return;
        this._subscription = input.subscribe((item) => {
            if (item !== this.context.ngVar) {
                this.context.ngVar = item;
                this.cdr.markForCheck();
            }
        });
    }

    static ngTemplateGuard_ngVar: "binding";

    static ngTemplateContextGuard<T>(dir: NgVar<T>, ctx: NgVarContext<T>): ctx is NgVarContext<T> {
        return true;
    }
}

【问题讨论】:

    标签: angular


    【解决方案1】:

    如果你不知道(写这个作为答案,因为我不能以

    见:https://twitter.com/angular/status/1357403631901937672

    【讨论】:

    • 现在你可以写 cmets 了 :)
    【解决方案2】:

    是我,OP

    指令没有问题。

    问题是 Angular 语言服务尚未更新以推断这些类型(他们最近宣布它支持常春藤,所以我希望这应该在几个月内工作)。

    我会在修复后更新答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      • 2017-10-18
      相关资源
      最近更新 更多