[英]Angular 4 get dom element
嗨,我想在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;
}
您需要訪問nativeElement
您在中定義的元素屬性@ViewChild
申報操縱實際的DOM元素。 單獨調用@ViewChild ElementRef
為DOM中的元素創建一個ElementRef
。 因此,你為什么要訪問nativeElement
的財產ElementRef
操作DOM元素。 例如:
ngAfterViewInit() {
console.log(this.nameInput.nativeElement);
}
根據您的代碼,只有當editable
為true時, nameInput
才會出現。 此處,您可以將editable的默認值設置為false( public editable: boolean = false
)。 所以元素甚至不存在於DOM中,這就是為什么即使你在ngAfterViewInit
調用它也會給你未定義的原因。
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.