Last active
January 10, 2019 11:08
-
-
Save wildlarva/6ad73b6a31e2c85ad852a6cf16ce94b6 to your computer and use it in GitHub Desktop.
Focus conditional input element on Angular
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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