我正在使用Angular 5开发一个前端应用程序,我需要隐藏一个搜索框,但只要点击一个按钮,搜索框就会显示并聚焦.

我try 了一些使用指令或其他方法在StackOverflow上找到的方法,但没有成功.

以下是示例代码:

@Component({
   selector: 'my-app',
   template: `
    <div>
    <h2>Hello</h2>
    </div>
    <button (click) ="showSearch()">Show Search</button>
    <p></p>
    <form>
      <div >
        <input *ngIf="show" #search type="text"  />            
      </div>
    </form>
    `,
  })
  export class App implements AfterViewInit {
  @ViewChild('search') searchElement: ElementRef;

  show: false;
  name:string;
  constructor() {    
  }

  showSearch(){
    this.show = !this.show;    
    this.searchElement.nativeElement.focus();
    alert("focus");
  }

  ngAfterViewInit() {
    this.firstNameElement.nativeElement.focus();
  }

搜索框未设置为焦点.

我怎么才能做到这一点呢?

推荐答案

如下所示修改show search方法

showSearch(){
  this.show = !this.show;  
  setTimeout(()=>{ // this will make the execution after the above boolean has changed
    this.searchElement.nativeElement.focus();
  },0);  
}

Angular相关问答推荐

PrimeNG侧栏清除primeNG消息.为什么?

如何在Angular中执行一个操作条件为多个可观测值?

如何在HTML外部项目中使用Web组件(以17角创建)

命令不起作用的初始菜单项

如何包装NGB carousel ?

有Angular react 形式的输入用货币管

HTTP POST响应失败Angular 16

天使17中的倒计时器

如何防止打印后的空格后的HTML元素的Angular ?

将ngModel绑定到@Input属性是不是一种糟糕的做法?

ngx-http-client 在 Angular 16 中已弃用

当try 关闭浏览器选项卡时显示alert 时,我是否可以捕获用户是否取消警告

无法在 Angular 中使用 CryptoJS 正确加密

将 html ngModel 值传递给服务Angular

Angular/RxJS 6:如何防止重复的 HTTP 请求?

Angular 2: Debounce(ngModelChange)?

等待多个promises完成

@HostBinding 与 Angular 中的变量类

如何在 Angular 2 中链接 HTTP 调用?

如何在 Angular 中使用带有 SASS 的 Bootstrap 4