Hi i'm trying to set focus on an input element once the edit button is clicked on an Angular 4 application.
First i tried Renderer2, but it doesn't seem to work for this purpose.
Now I'm trying to get it using @ViewChild, I'm always getting value as undefined.
I event tried implementing AfterViewInit and logging the element immediately once loaded, but still I'm getting '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 have removed the code where i tried to set focus.
edit(el) {
console.log(el);
console.log(this.nameInput);
this.nameInput.focus();
this.editable = true;
this.name = this.artist.name;
}