【发布时间】:2017-07-30 03:42:21
【问题描述】:
您好,我正在尝试在 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;
}
【问题讨论】:
标签: angular typescript single-page-application