首页 > 解决方案 > Angular 结构指令上下文模板类型检查

问题描述

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

<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

解决方案


如果你不知道(写这个作为答案,因为我不能评论 <50 的声誉):如果你在 vscode 中启用实验性的常春藤语言服务,这已经对我有用:基本上与此处编写的实现相同。

在此处输入图像描述

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


推荐阅读