忽略用于angular的模板错误

时间:2019-06-08 12:10:47

标签: angular typescript

我正在使用此lib

tl; dr:如何忽略打字稿中的“未定义属性”

为了创建一个自定义标签,文档说要查看其实现,我复制了它们的基本代码,模板看起来像这样=>

<ac-html *ngIf="plonterService.plonterShown" [props]="{
  position: plonterPosition
}">
  <div class="plonter-context-menu">
    <div *ngFor="let entity of plonterService.entitesToPlonter">
      <div class="plonter-item" (click)="chooseEntity(entity)">

        {{ entity?.name || entity?.id }}
      </div>
    </div>
  </div>
</ac-html>

组件

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { CoordinateConverter, PlonterService } from 'angular-cesium';

@Component({
  selector: 'app-entity-plonter',
  templateUrl: './entity-plonter.component.html',
  styleUrls: ['./entity-plonter.component.less'],
  providers: [CoordinateConverter],
})
export class EntityPlonterComponent implements OnInit {

  constructor(public plonterService: PlonterService,
              private chandeDetector: ChangeDetectorRef,
              private coordinateConverter: CoordinateConverter) { }

  ngOnInit() {
    this.plonterService.plonterChangeNotifier.subscribe(() => this.chandeDetector.detectChanges());
  }

  get plonterPosition() {
    if (this.plonterService.plonterShown) {
      const screenPos = this.plonterService.plonterClickPosition.endPosition;
      return this.coordinateConverter.screenToCartesian3(screenPos);
    }
  }

  chooseEntity(entity: any) {
    this.plonterService.resolvePlonter(entity);
  }
}

现在,我在线的模板中有错误

{{ entity?.name || entity?.id }}

AcEntity没有属性名称和ID。

这是因为在lib中,AcEntity的定义是这样的

/**
 * Angular Cesium parent entity, all entities should inherit from it.
 * ```typescript
 * entity= new AcEntity({
 *      id: 0,
 *      name: 'click me',
 *      position: Cesium.Cartesian3.fromRadians(0.5, 0.5),
 * });
 * ```
 */
export class AcEntity {

  /**
   * Creates entity from a json
   * @param json entity object
   * @returns entity as AcEntity
   */
  static create(json?: any) {
    if (json) {
      return Object.assign(new AcEntity(), json);
    }
    return new AcEntity();
  }

  /**
   * Creates entity from a json
   * @param json (Optional) entity object
   */
  constructor(json?: any) {
    Object.assign(this, json);
  }
}

现在,我知道错误是合法的,但是对于编译和构建,我想忽略它。由于我无法直接控制该库,因此价值来自该库的服务。

有可能吗?

2 个答案:

答案 0 :(得分:4)

我不知道是否有人还在寻找答案,只是以为我会添加找到的答案。您可以通过用$ any(object)包装对象来避免模板错误。因此,在这种情况下,它看起来像:

<div *ngFor="let entity of $any(plonterService).entitesToPlonter">

答案 1 :(得分:0)

您可以尝试'any'-

<div *ngFor="let entity of plonterService.entitesToPlonter as any">
      <div class="plonter-item" (click)="chooseEntity(entity)">

        {{ entity?.name || entity?.id }}
      </div>
</div>

请参阅以下stackblitz示例-

https://stackblitz.com/edit/angular-ssdwmx?file=app%2Fbutton-overview-example.html