HTML5 event handling(onfocus and onfocusout) using angular 2

前端 未结 5 1640
逝去的感伤
逝去的感伤 2020-12-02 13:46

I have a date field and I want to remove the place holder by default.

I am using javascript onfocus and onfocusout events for removing pl

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 14:34

    If you want to catch the focus event dynamiclly on every input on your component :

    import { AfterViewInit, Component, ElementRef } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent implements AfterViewInit {
    
      constructor(private el: ElementRef) {
      }
    
      ngAfterViewInit() {
           // document.getElementsByTagName('input') : to gell all Docuement imputs
           const inputList = [].slice.call((this.el.nativeElement).getElementsByTagName('input'));
            inputList.forEach((input: HTMLElement) => {
                input.addEventListener('focus', () => {
                    input.setAttribute('placeholder', 'focused');
                });
                input.addEventListener('blur', () => {
                    input.removeAttribute('placeholder');
                });
            });
        }
    }
    

    Checkout the full code here : https://stackblitz.com/edit/angular-93jdir

提交回复
热议问题