【问题标题】:Document is undefined Angular文档未定义 Angular
【发布时间】:2020-07-09 16:53:18
【问题描述】:

我的 html 中有这段代码,用于在单击此 div 时触发文件输入。目前我收到一个错误,即文档未定义,但是当我添加断点并观察文档变量时,我发现它实际上是在此 html 运行时定义的。我正在使用角度框架。

  <input id="file-input" type="file" name="name" style="display: none;" />
  <div class="csvBox" id="csvBox" (click)="document.getElementById('file-input').click();">

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    模板只能访问组件属性。 document 不是一个。

    此外,您永远不应该在 Angular 中使用 document.getElementById。您可以像这样使用模板变量:

    <input #fileInput type="file" name="name" style="display: none;" />
    <div class="csvBox" id="csvBox" (click)="fileInput.click()">
    

    【讨论】:

      【解决方案2】:

      听起来你需要从 Angular 导入文档。

      import { Inject, Injectable } from '@angular/core';
      import { DOCUMENT } from '@angular/common';
      
      @Component()
       export class MyService {
       constructor(@Inject(DOCUMENT) private document: Document) {}
      } 
      

      【讨论】:

        猜你喜欢
        • 2018-02-04
        • 1970-01-01
        • 2022-01-06
        • 2016-05-06
        • 2020-10-26
        • 2015-11-14
        • 2019-11-28
        相关资源
        最近更新 更多