【问题标题】:How to type a variable for ngfor for html template in Angular?如何在 Angular 中为 ngfor 为 html 模板键入变量?
【发布时间】:2021-08-14 09:04:48
【问题描述】:

我的组件中有这个变量:

  sizes: {[key: string]: GoodModel[]};

在控制器中,我的 IDE 处理得很好。例如,可以键入:

  this.sizes['5'][0].brand;

然后你在brand上按f12,IDE显示GoodModel类的brand字段。

但是当我在 HTML 中执行 *ngFor 时它不起作用:

  <div *ngFor="let size of sizes[radius]">
    <a [routerLink]="size.brand.url></a>
  </div>

IDE 对 size.brand 和 size.brand.url 字段一无所知。

我认为,也许存在某种处理它的方法。有这样的想法:

  <div *ngFor="let size of sizes[radius] as GoodModel">

有没有办法在 HTML 模板中输入这个变量?

【问题讨论】:

    标签: javascript html angular typescript ngfor


    【解决方案1】:

    您可以为*ngFor呈现的模板创建一个新组件,然后您可以键入

    来自此答案的代码:Is there a way to declare a specific type in ngFor

    容器模板:

    <ng-container *ngFor="item of items" >
      <my-custom-component [item]="item"></my-custom-component>
    </ng-container>
    

    自定义组件模板:

    <div *ngIf="item.menuItemType == 'dropdown'">
      <!-- -->
    </div>
    

    .ts文件:

    @Component({})
    export class MyCustomComponent {
      @Input() item: MenuItem
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-27
      • 1970-01-01
      • 2018-06-24
      • 2017-08-02
      • 2017-11-10
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      相关资源
      最近更新 更多