如何修复 Angular Can't bind to 'data-...' since it isn't a known property of ...

问题

编译 Angular 应用时,你看到如下错误:

angular_error_output.txt
✘ [ERROR] NG8002: Can't bind to 'data-sensor' since it isn't a known property of 'div'. [plugin angular-compiler]

    src/app/my-component/my-component.component.html:107:39:
      107 │ ...                <div class="sensor" [data-sensor]="sensor | json">
          ╵                                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  Error occurs in the template of component NoxecoDepolMeasurementDisplayComponent.

    src/app/my-component/my-component.component.ts:31:17:
      31 │     templateUrl: './my-component.component.html',
         ╵                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

解决方案

当你尝试绑定 Angular 不知道的属性时会出现此错误。

这是 data-... 属性,所以 Angular 不需要专门知道它。但为了避免触发类型检查器,使用 attr.data-sensor 代替:

my-component.component.html
<div class="sensor" [attr.data-sensor]="sensor | json">

这样,Angular 知道这是属性绑定而不是属性绑定。


Check out similar posts by category: Angular, Typescript