【问题标题】:unable to access template reference variable inside *ngIf无法访问 *ngIf 中的模板引用变量
【发布时间】:2019-07-20 15:06:04
【问题描述】:

我在屏幕截图中显示以下错误。

当我单击搜索链接时,我正在显示搜索输入,我正在使用 keyup 事件从输入中获取值。但是得到屏幕截图中显示的错误。 我正在使用角度 6。

组件

import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { fromEvent } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-temp',
  templateUrl: './temp.component.html',
  styleUrls: ['./temp.component.css']
})
export class TempComponent implements OnInit, AfterViewInit {
  displaySearch = false;
  @ViewChild('searchValue') searchValue: ElementRef;
  constructor() { }

  ngOnInit() {
  }

   searchFunc() {
      if (this.displaySearch === false) {
          this.displaySearch = true;
      } else if (this.displaySearch === true){
          this.displaySearch = false;
   }

}

  ngAfterViewInit() {
    fromEvent(this.searchValue.nativeElement, 'keyup').pipe(
      map((event: any) => {
        return (event.target).value;
      })
    ).subscribe(res => {
      console.log(res);
    });
  }
}

HTML

<div>
  <a href="javascript:void(0)" (click)="searchFunc()">Search</a>
</div>

<ng-container *ngIf="displaySearch">
  <input type="text" name="searchValue" #searchValue>
</ng-container>

【问题讨论】:

  • ts 文件中的 searchFunc() 在哪里?
  • 它在组件中,此刻我想读取组件中的值。
  • 我正在尝试使用 fromEvent() 运算符读取值。
  • 但是兄弟你在 a 标签中写了 searchFunc() 但是我在你的 ts 文件中看不到 searchFunc() 那么你怎么能改变 displaySearch 的值。
  • 兄弟,你能在 stackblitz 中制作这个项目吗?

标签: angular


【解决方案1】:

您不能在 ngAfterViewInit() 中使用 this.searchValue.nativeElement。 原因是当 TempComponent 加载时 searchValue 输入不在 DOM 作为 displaySearch strong> 当时是 false。在 displaySearch 变为 true 之后,您应该使用 nativeElement。 如下更改您的代码。

   searchFunc() {
    this.displaySearch = true;
    setTimeout(() => {

    fromEvent(this.searchValue.nativeElement, 'keyup').pipe(
      map((event: any) => {
        return (event.target).value;
      })
    ).subscribe(res => {
      console.log(res);
    });

    },3000);
  }

【讨论】:

    【解决方案2】:

    这是意料之中的。

    ngAfterViewInit 将在视图初始化后立即运行。只有在单击搜索链接后,您的 searchValue 模板变量才会出现。而在ngAfterViewInit 方法中,您正在尝试读取nativeElement 的某些内容,而此时该内容尚未定义。

    因此错误。

    更新:

    通过读取来自 @ViewChild 的数据,您给自己带来了不必要的困难。

    使用事件绑定语法在input 字段上监听keyup 事件怎么样:

    <div *ngIf="displaySearch">
        <input 
        type="text" 
        name="searchValue" 
        (keyup)="onKeyUp($event.target.value)" />
    </div>
    

    你会得到onKeyUp方法中的值。

    注意: Vega 建议的解决方案也是一个很好的解决方案。但它不会很好地扩展。因为ngAfterViewChecked 方法在每个变更检测周期都会被调用。所以我不建议使用它。


    这里有一个Working Sample StackBlitz 供您参考。

    【讨论】:

    • 如何在上述情况下获取模板引用变量值,如果搜索框可见我想读取它的值。
    • 具体用例是什么?你想用这个来达到什么目的?如果您能对此提供一些说明,我们将能够为您提供帮助。
    • @SiddAjmera,此代码是演示代码,但在我的实际项目中,使用条件 *ngIf 显示了一个 html 块,在此 html 块中有一个带有模板引用变量的搜索框。希望通过 keyup 事件读取输入的值。
    猜你喜欢
    • 2017-12-28
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 2017-10-17
    • 1970-01-01
    相关资源
    最近更新 更多