Skip to content

Instantly share code, notes, and snippets.

@wildlarva
Last active January 10, 2019 11:08
Show Gist options
  • Save wildlarva/6ad73b6a31e2c85ad852a6cf16ce94b6 to your computer and use it in GitHub Desktop.
Save wildlarva/6ad73b6a31e2c85ad852a6cf16ce94b6 to your computer and use it in GitHub Desktop.
Focus conditional input element on Angular
<div *ngFor="let task of tasks">
<!-- Use # to set the name of the input element to focus -->
<input #taskInput *ngIf="task.isEditing" type="text" [(ngModel)]="task.name" (blur)="onEdited(task)" (keyup.enter)="taskInput.blur()">
<div *ngIf="!task.isEditing" (dblclick)="onEdit(task)">{{task.name}}</div>
</div>
import { Component, OnInit, ElementRef, ViewChildren, QueryList, AfterViewInit } from '@angular/core';
import {Task} from './task/task';
import {TaskService} from './task/task.service';
@Component({
selector: 'focus-input-element-component',
templateUrl: './focus-input-element-component.html',
styleUrls: ['./focus-input-element-component.css'],
})
export class AppComponent implements OnInit, AfterViewInit {
private tasks: Task[];
// Refer the input element to focus
@ViewChildren("taskInput") private taskInput: QueryList<ElementRef>;
constructor(private taskService: TaskService) {
}
ngOnInit(): void {
this.taskService.getTasks()
.subscribe(tasks => this.tasks = tasks);
}
ngAfterViewInit(): void {
// Subscribe to the changes of the input elements and focus them
this.taskInput.changes.subscribe(_ => this.focusTaskInput());
}
focusTaskInput() {
if (this.taskInput.length > 0) {
this.taskInput.first.nativeElement.focus();
}
}
onEdit(task: Task) {
task.isEditing = true;
}
onEdited(task: Task) {
task.isEditing = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment