首页 > 解决方案 > 无法编译 HTMLCollectionOf

问题描述

我正在编写一个电子商务应用程序,所以当点击添加到购物车时我会弹出一个用户弹出窗口,允许用户选择用户想要添加的产品的种类和数量。弹出窗口包括一个选择表单和一个数字输入。然后我必须访问这些输入的内容以在购物车中显示适当的信息。

我尝试使用以下方式访问信息:

let input = (<HTMLInputElement>document.getElementsByClassName('number_input'));

但这给出了这个错误:

src/app/layout/products/products.component.ts(93,18) 中的错误:错误 TS2352:“HTMLCollectionOf”类型无法转换为“HTMLInputElement”类型。“HTMLCollectionOf”类型中缺少属性“accept”。src/app/layout/products/products.component.ts(111,14):错误 TS2352:类型“HTMLCollectionOf”无法转换为类型“HTMLInputElement”。

编译失败

Visual Studio 建议我包括unknown除了HTMLInputElement访问信息之外,所以我尝试了:

let input = (<HTMLInputElement><unknown>document.getElementsByClassName('number_input'));

但这给出了这个错误:

src/app/layout/products/products.component.ts(91,37) 中的错误:错误 TS2304:找不到名称“未知”。src/app/layout/products/products.component.ts(109,33):错误 TS2304:找不到名称“未知”。

这是我输入的代码。它利用引导程序中的模态

<div class="modal fade" id="variedades_y_cantidades" tabindex="-1" role="dialog" aria-labelledby="ModalCenterTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="bebida_descripcion">AGREGAR {{ bebida.descripcion }}</h5>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col"><div class="form-group">
              <label for="variadedes">Variaded:</label>
                <select class="form-control" id="variadedes">
                    <option *ngFor="let detalle of detalle_bebida">{{detalle.variedad}}</option>
              </select>
          </div></div>
          <div class="row"><div class="col">Cantidad: <input type="number" name="cantidad" min="1" style="width: 70px;" class="number_input" value="1"></div></div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">CERRAR</button>
        <button type="button" class="btn btn-primary" (click)="onModalAgregarClick($event)" data-dismiss="modal">AGREGAR</button>
      </div>
    </div>
  </div>
</div>

我希望能够在没有任何错误的情况下访问数据,以便编译应用程序以运行。

标签: javascripthtmlangulartypescript

解决方案


您收到编译错误,因为您试图将 anHTMLCollection转换为HTMLElement.

您的调用document.getElementsByClassName()不返回一个HtmlElement,它返回一个HTMLCollection以下是 Mozilla 提供的有关此功能的一些有用文档。您需要更新您的演员表,然后访问该集合的第一个元素(如果它存在的话)。

let numberInputs: HTMLCollection = document.getElementsByClassName('number_input');
let firstNumberInput: HTMLSelectElement = numberInputs[0];
console.log(firstNumberInput.value);

话虽如此,在使用 Angular 时,强烈建议在这种情况下使用指令。我会改为使用[(ngModel)]指令或构建反应形式来访问输入的值。


推荐阅读