【问题标题】:Angular: Type checking in templates not working correctlyAngular:类型检查模板无法正常工作
【发布时间】:2020-05-08 09:43:27
【问题描述】:

由于一段时间以来,类型检查在 VSCode 中的 Angular 模板中不起作用。

我有以下代码:

<div *ngIf="activeProperty" class="mx-3">
    <!-- some other code -->
    <input
        required
        id="propertyName"
        type="text"
        class="form-control"
        name="propertyName"
        [ngModel]="activeProperty.uiProperty.label"
        (ngModelChange)="updateLabelAndKeyInSpec($event)"
    />
</div>

现在在这一行:

[ngModel]="activeProperty.uiProperty.label"

activeProperty 带有下划线,告诉我The expression might be null 这显然是错误的,因为我正在通过上面的*ngIf 进行检查。

请在此处查看我的ng --version

    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 8.3.6
Node: 12.7.0
OS: win32 x64
Angular: 8.2.8
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.803.6
@angular-devkit/build-angular     0.803.6
@angular-devkit/build-optimizer   0.803.6
@angular-devkit/build-webpack     0.803.6
@angular-devkit/core              8.3.6
@angular-devkit/schematics        8.3.6
@angular/cdk                      8.2.2
@angular/cli                      8.3.6
@angular/http                     7.2.15
@ngtools/webpack                  8.3.6
@schematics/angular               8.3.6
@schematics/update                0.803.6
rxjs                              6.5.3
typescript                        3.5.3
webpack                           4.39.2

我做错了吗?

【问题讨论】:

  • 表达式可能为空 - 你从哪里得到这个错误?
  • VS Code 在抱怨,所以我认为这是 tslint 错误
  • [ngModel]="activeProperty?.uiProperty?.label" 你可以试试这个方法吗。
  • @hrdkisback 谢谢,但我以前读过这个。如您所见,*ngIf 并没有解决我的问题。

标签: html angular typescript tslint


【解决方案1】:

我无法详细告诉你为什么它被下划线......也许是因为它不知道*ngIf 左右......但这应该可以解决问题:

[ngModel]="activeProperty?.uiProperty?.label"

【讨论】:

  • 这行得通,谢谢。但是,当我使用双向绑定 ([(ngModel)]) 时,我无法使用问号。你有解决方案吗?
  • 我想不出你不能在那里使用它的原因......你能分享你的 tslint.json 吗? jsonblob.com
  • 它给了我一个错误Parser Error: The '?.' operator cannot be used in the assignment at column 31 in [activeProperty?.uiControlType=$event] in ... 我的 tslint 很大,但如果它有助于调试,我可以分享它。请告诉我:)
  • 你是这样写的:&lt;input [(ngModel)]="activeProperty?.uiProperty?.label"&gt; 对吧?错误来自哪里? tslint 还是其他地方?
  • 在哪里?请检查我的帖子,我只有一个 [ngModel] 绑定。
【解决方案2】:

你可以使用 activeProperty!.uiProperty!.label

【讨论】:

    【解决方案3】:
    [(ngModel)]="activeProperty.uiProperty.label"
    

    你可以试试这个吗?

    【讨论】:

    • 这只是绑定,不幸的是与该问题无关
    猜你喜欢
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    • 2017-07-01
    • 2015-06-04
    相关资源
    最近更新 更多