Hi, I am trying to adjust focus on an input element after clicking an edit button in an Angular 4 application.
At first I tried Renderer2, but for this purpose it does not work.
Now I'm trying to get it using @ViewChild, I always get the value as undefined.
EventI tried to embed AfterViewInit and register the item immediately after loading, but still I get 'undefined'. Please, help..
import { Component, OnInit, Input, Output, EventEmitter, Renderer2, ViewChild, AfterViewInit } from '@angular/core';
import { NgIf } from '@angular/common';
import { DataService } from '../data.service';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-artist-list-item',
template: `
<button class="w3-button w3-circle w3-orange" (click)="edit(nameInput)"><i class="fa fa-pencil"></i></button>
<span *ngIf="editable">
<input class="name" #nameInput (keyup)="onKey(nameInput.value)" (keypress)="inputEnter($event)" [value]="artist.name">
<button class="w3-button w3-green btn-save" (click)="save()">Save</button>
</span>
<span *ngIf="!editable">
{{artist.name}}
</span>
`,
styleUrls: ['./artist-list-item.component.scss']
})
export class ArtistListItemComponent implements OnInit, AfterViewInit {
@Input() artist: any;
@Output() onDelete = new EventEmitter();
@Output() onEdit = new EventEmitter();
@Output() onSave = new EventEmitter();
@ViewChild('nameInput') nameInput;
public editable: boolean = false;
name: any = '';
constructor(private Data: DataService, private rd: Renderer2) { }
ngAfterViewInit() {
console.log(this.nameInput);
}
ngOnInit() {
}
edit(el) {
console.log(el);
console.log(this.nameInput);
this.editable = true;
this.name = this.artist.name;
}
}
By the way, I deleted the code where I tried to set the focus.
edit(el) {
console.log(el);
console.log(this.nameInput);
this.nameInput.focus();
this.editable = true;
this.name = this.artist.name;
}
source
share