【问题标题】:Why is nativeElement of elementRef undefined?为什么 elementRef 的 nativeElement 未定义?
【发布时间】:2020-06-20 16:12:50
【问题描述】:
<div class="parent">
            <div class="input-group">
            <input  [(ngModel)]="InputValue" 
              #Field (input)="changedEvent()" (focus)="onFocus()" />
            <button (click)="changedEvent()">click</button>
            </div>
    
            <div #Container *ngIf="isFocused">
              // a table
            </div>

</div>

使用上面的代码,我尝试在 changedEvent() 方法中访问 elementRefs #Field 和 #Container 的 nativeElement,如下所示:

  //this is how they have been declared in the component
  @ViewChild('Container', { static: false }) Container: ElementRef;
  @ViewChild('Field', { static: false }) Field: ElementRef;

  //inside the method
  const element = this.Field.nativeElement;
  const list = this.Container.nativeElement;

当转到此方法时,当触发文本字段的输入侦听器时,它可以正常工作。但是,当单击按钮并转到此处时,Container ElementRef 未定义。 (字段已定义)。 想知道我在输入侦听器的工作位置上缺少什么,但在点击侦听器的指导下却没有。

【问题讨论】:

  • this.Container.nativeElement语句执行时,你确定isFocused是真的吗?

标签: javascript html angular


【解决方案1】:

似乎 Container 元素由于 *ngIf 而未渲染,而 Angular 无法引用它,因为尚未渲染。如果您不希望元素可见但希望引用有效,请尝试使用 [hidden]="!isFocused"

【讨论】:

    猜你喜欢
    • 2018-06-03
    • 2019-05-01
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 2018-06-15
    • 2017-12-09
    • 2021-07-10
    • 1970-01-01
    相关资源
    最近更新 更多