【问题标题】:How to focus on newly added input in Angular 2? [duplicate]如何专注于 Angular 2 中新增的输入? [复制]
【发布时间】:2017-04-09 15:52:04
【问题描述】:

我的模板

    @ViewChildren('search') searchInput: QueryList<any>;

    toggleSearch(){
        this.showSearch = !this.showSearch;
        if (this.showSearch){
            console.log(this.searchInput.first); <= undefined
        }
    }
			<li class="search" *ngIf="showSearch" >
				<i class="news-admin-icon news-admin-search"></i>
				<input (blur)="toggleSearch()" #search (keyup)="searchNews(search.value)" type="text" placeholder="Search">
			</li>
			</li>
			<li class="special" *ngIf="!showSearch" (click)="toggleSearch(search)">
				<a href="#"><i class="news-admin-icon news-admin-search"></i>  Search</a>
			</li>

我尝试使用 @ViewChild 进行“搜索”但未定义 当我尝试使用@ViewChildren 进行“搜索”时,我得到了

QueryList_dirty: false_emitter: EventEmitter_results: Array[1]changes: (...)dirty: (...)first: (...)last: (...)length: (...)proto:对象

【问题讨论】:

    标签: angular


    【解决方案1】:

    尝试添加这个:

    ngAfterViewChecked() {  // Called after child views changed
      if(this.showSearch && this.searchInput.first) {  // check is showSearch and ViewChildren has result
        this.searchInput.first.nativeElement.focus();  // set focus on native input element
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-07
      • 1970-01-01
      • 2018-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多