【问题标题】:Why do I get an 'undefined' error in regards to the data in my Angular template?为什么我的 Angular 模板中的数据会出现“未定义”错误?
【发布时间】:2021-11-26 02:20:57
【问题描述】:

我正在尝试在我的 Angular 11 应用程序中创建一个模板,但它无法识别其中的数据。

我们有一个剑道网格,我们希望第一列包含一个按钮,单击该按钮会弹出一个菜单。所以我创建了一个组件来充当按钮和菜单:

如您所见,菜单中有 3 个项目。但是我们网站中的一些网格需要的不仅仅是这 3 个项目。他们需要网格独有的项目。我没有为菜单提供网格可能需要的所有可能项目(如果不需要则隐藏它们),我试图将它们作为模板从包含网格的组件添加到菜单中。

这是我的做法:

<kendo-grid [data]="data" ... >
  <kendo-grid-column ... >
    <ng-template kendoGridCellTemplate let-dataItem>

      <!-- MY TEMPLATE -->
      <ng-template #customMenuItemsTemplate let-dataItem="dataItem">
        <button mat-menu-item *ngIf="dataItem.hpi?.id" ... >
          <mat-icon>...</mat-icon>
        </button>
      </ng-template>
    
      <!-- MY BUTTON & MENU COMPONENT -->
      <app-command-menu
        [contentTemplate]="customMenuItemsTemplate"
        [hpiId]="dataItem.hpi.id"
        ...
      ></app-command-menu>
      
    </ng-template>
  </kendo-grid-column>
</kendo-grid>

如您所见,我在网格内定义了我的模板(确切地说是在 kendoGridCellTemplate 内)。我在 app-command-menu 组件之前定义它。我给模板一个引用标签#customMenuItemsTemplate 并使用该引用将模板绑定到命令菜单组件中的[contentTemplate]。我在网格中添加了模板,所以它知道 dataItem 是什么。然而,我在控制台中不断收到错误消息:

Cannot read properties of undefined (reading 'hpi')

在我添加模板之前,应用程序的 dataItem 没有问题。如您所见,我在命令菜单组件中将dataItem.hpi.id 绑定到[hpiId]。在我添加模板之前就在那里,它工作得很好。为什么要为组件而不是模板定义 dataItem,即使它们都在网格中的同一位置?是不是因为模板中的值只能从组件内部(即注入后)读取,而不是从带有网格的页面读取?

如果您需要更多代码示例或更多解释,请告诉我。

【问题讨论】:

    标签: angular templates components kendo-grid


    【解决方案1】:

    问题的解决方案非常简单。我不得不从我的模板中删除let-dataItem="dataItem"。所以这个:

    <ng-template #customMenuItemsTemplate let-dataItem="dataItem">
    ...
    </ng-template>
    

    转换成这个:

    <ng-template #customMenuItemsTemplate>
    ...
    </ng-template>
    

    我不确定为什么会这样。我认为使用let-dataItem="dataItem" 设置 dataItem 充其量是无害的,但显然,它会导致 Angular 不知道 dataItem 是什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-08
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 2022-01-22
      • 2014-04-17
      • 1970-01-01
      • 2012-01-30
      相关资源
      最近更新 更多