Angular 4获得dom元素

前端之家收集整理的这篇文章主要介绍了Angular 4获得dom元素前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
嗨,我想在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;
            }
根据您的代码,只有当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>
原文链接:https://www.f2er.com/angularjs/140963.html

猜你在找的Angularjs相关文章