【问题标题】:Angular template variable used to disable button throws compile error用于禁用按钮的 Angular 模板变量引发编译错误
【发布时间】:2020-12-28 15:13:23
【问题描述】:

我正在尝试使用 Angular 模板变量将值传递给调用后端的按钮。当我编译下面的代码时,我得到一个错误。为什么角度模板会引发错误?我在这里使用了文档中的一个示例:https://angular.io/guide/template-reference-variables

我猜可能是因为:

结构指令 *ngFor 实例化模板两次,因为 *ngFor 迭代数组中的两个项目。无法定义 ref.value 引用的含义。

但是我不明白....所选选项不是被实例化的选项吗?如果它没有被实例化,它不会是未定义的吗?

ERROR in src/app/statusview/statusview.component.html:84:96 - error TS2339: Property 'endo' does not exist on type 'StatusviewComponent'.

84                         <button mat-raised-button color="primary" (click)="ReloadOdataEndpoint(endo.value)"

代码

                <select>
                    <option *ngFor="let t of selectedCustomer.endpoints" #endo [ngValue]="t.name">
                        {{t.name}}
                    </option>
                </select>
                <button mat-raised-button color="primary" (click)="ReloadEndpoint(endo.value)"
                    disabled="!endo" style="margin: 5px;">
                    Load Endpoint
                </button>

注意:这些变量都没有在模板中声明——我试图在 html 中设置它们并在模板中传递它们

【问题讨论】:

  • 就像错误提示的那样,您的组件类中是否有一个名为 endo 的属性?
  • endo 由模板初始化,如他所示,您需要将#endo 设置为选择元素而不是选项
  • @Rilcon42 不应将模板变量设置为选择,而不是选项..您基本上想获得选定的选项值。
  • @ulmas 我没有在组件中声明 endo 属性。我试图在 HTML 中声明它并在单击按钮时将其传递给组件

标签: angular angular-template


【解决方案1】:

你不能引用一个选项元素,你会有一个引用多个元素。 将其放在 select 上并选择值。

<select #endo>
  <option *ngFor="let t of selectedCustomer.endpoints" [ngValue]="t.name">
   {{t.name}}
  </option>
</select>
<button mat-raised-button color="primary" (click)="ReloadEndpoint(endo.value)" disabled="!endo" style="margin: 5px;">
 Load Endpoint
</button>

【讨论】:

    猜你喜欢
    • 2019-02-01
    • 2018-07-14
    • 2017-04-27
    • 2019-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多