无法访问* ngIf中的模板引用变量

拉曼

我在屏幕快照中显示以下错误。 在此处输入图片说明

当我单击搜索链接时,我正在显示搜索输入,正在使用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>
苏达珊娜·达亚南达(Sudarshana Dayananda)

您不能this.searchValue.nativeElement在中使用ngAfterViewInit()其原因是,当TempComponent加载searchValue输入是不是在DOMdisplaySearchfalse在那个时候。成为nativeElement之后,您应该使用如下更改代码。displaySearchtrue

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

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

    },3000);
  }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章