【问题标题】:Is there a way to declare a specific type in ngFor有没有办法在 ngFor 中声明特定类型
【发布时间】:2018-02-23 18:53:30
【问题描述】:

我正在使用 ngFor 在 Angular 4.x 中迭代特定类型 [Menu] 的集合

然后在菜单对象 [menu.items] 的集合属性上循环

不幸的是,在我的 IDE [Eclipse + Angular IDE] 中该属性是未知的,即使 Menu 类将 items 属性定义为 MenuItem 的数组。

有什么想法吗?

相关类声明 -

export class MenuBase {
  id: string;
  title: string;
  isPublic: boolean;
  roles: string[];
  items: MenuItem[];
  position: number;
// rest of class omitted
}

export class MenuItem extends MenuBase {
  menuItemType: MenuItemType;
  callback: () => void;
  location: string;

  constructor (options: any) {
    super(options);
    this.location = options.location;
    this.menuItemType = options.menuItemType || MenuItemType.location;
    this.callback = options.callback;
  }
}

export class Menu extends MenuBase {
  constructor (options: any) {
    super(options);
  }
}

附加信息 - 这是我正在从事的项目: https://github.com/savantly-net/ngx-menu
该项目将在 Eclipse 中显示一个错误,即使它是有效的。

我从未创建过任何文档,但我在这里使用了它 -
https://github.com/savantly-net/sprout-platform/tree/master/web/sprout-web-ui

【问题讨论】:

  • 如果能像 *ngFor="let item: MenuItem of menu.items" 这样声明类型就好了
  • 不,那不可能。
  • 这是 AngularIDE 的一个已知问题。如果正确完成,代码应该仍然可以工作:genuitec.com/forums/topic/…
  • 这个问题还没有解决办法吗?刚开始学习Angular 6/7,好像没解决。
  • 如果您使用的是 VS Code 或 WebStorm,那么此链接可能会对您有所帮助:angular.io/guide/language-service。本质上,在 VS Code 中,您安装扩展“Angular 语言服务”,然后在 html 文件中获得自动完成功能。在 WebStorm 中,您必须将其安装为开发依赖项@angular/language-service。您仍然无法添加类型,但您将获得自动完成功能(这就是我假设您需要一种类型的原因):)

标签: angular typescript


【解决方案1】:

顺便说一句:在 VS Code 中,您需要在适当的 tsconfig.json 中指定它

"angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInputTypes": true,
}

【讨论】:

【解决方案2】:

我成功的是为模板创建了一个新组件,*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
}

【讨论】:

  • 和我做的一样。将模型传递给组件,并在组件内部将其定义为具体类型。不知道有没有更好的办法。
  • 它不能解决 Eclipse 的问题 ;) 但我会接受它,因为它可以工作,这是一个很好的做法。
  • 对于任何发现此问题的人:如果您计划升级到 Ivy,请不要使用此方法,因为 Ivy 在编译期间会因类型不匹配而失败。我们在使用上述方法的一个应用程序中打开了 Ivy,整个应用程序像圣诞树一样亮了起来,但出现了编译错误。
  • 我不确定我们是否可以建议不要使用这种方法,因为不管这个答案如何,这种方法通常是使用哑/演示组件的好习惯
猜你喜欢
  • 2021-06-15
  • 2013-01-18
  • 1970-01-01
  • 1970-01-01
  • 2012-01-21
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
相关资源
最近更新 更多