嗨,我正在尝试在Angular 4应用程序上单击编辑按钮后将焦点设置在输入元素上。
首先我尝试使用Renderer2,但它似乎不适用于此目的。
现在我正在尝试使用@ViewChild获取它,但我总是得到未定义的值。
我甚至尝试实现AfterViewInit并在加载后立即记录元素,但仍然得到“未定义”的结果。请帮帮我。
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;
}
}
顺便说一下,我已经删除了尝试设置焦点的代码。
edit(el) {
console.log(el);
console.log(this.nameInput);
this.nameInput.focus();
this.editable = true;
this.name = this.artist.name;
}