Подтвердить что ты не робот

Обработка событий HTML5 (onfocus и onfocusout) с помощью angular 2

У меня есть поле даты, и я хочу удалить держатель места по умолчанию.

Я использую javascript onfocus и onfocusout для удаления placeholder.

Может ли кто-нибудь помочь с использованием директивы angular2?

<input name="date" type="text" onfocus="(this.type='date')" onfocusout="(this.type='text')" class="dateinput">

Я пытаюсь решить таким образом, но у меня возникает проблема с сбросом типа поля ввода.

import { Directive, ElementRef, Input } from 'angular2/core';
@Directive({
    selector: '.dateinput', 
    host: {
    '(focus)': 'setInputFocus()',
    '(focusout)': 'setInputFocusOut()',
  }})

  export class MyDirective {
      constructor(el: ElementRef) { this.el = el.nativeElement; console.log(this.el);}

      setInputFocus(): void {
        //console.log(this.elementRef.nativeElement.value);
      }
  }
4b9b3361

Ответ 1

Попробуйте использовать (focus) и (focusout) вместо onfocus и onfocusout

как это: -

<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">

также вы можете использовать так: -

некоторые люди предпочитают альтернативный префикс on-, известный как каноническая форма:

<input name="date" type="text" on-focus="focusFunction()" on-focusout="focusOutFunction()">

Узнайте больше о привязке событий , см. здесь.

Вы должны использовать HostListner для своего варианта использования

Angular будет вызывать декорированный метод, когда хост-элемент генерирует указанное событие. @HostListener является декоратором для метода обратного вызова/обработчика события

Смотрите мой обновляющий рабочий Plunker.

Рабочий пример Working Plunker

Обновление

Некоторые другие события могут быть использованы в angular -

(focus)="myMethod()"
(blur)="myMethod()" 
(submit)="myMethod()"  
(scroll)="myMethod()"

Ответ 2

Если вы хотите динамически перехватывать событие фокуса на каждом входе вашего компонента:

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((<HTMLElement>this.el.nativeElement).getElementsByTagName('input'));
        inputList.forEach((input: HTMLElement) => {
            input.addEventListener('focus', () => {
                input.setAttribute('placeholder', 'focused');
            });
            input.addEventListener('blur', () => {
                input.removeAttribute('placeholder');
            });
        });
    }
}

Ознакомьтесь с полным кодом здесь: https://stackblitz.com/edit/angular-93jdir

Ответ 3

Я создал небольшую директиву, которая связывается с атрибутом tabindex. Он добавляет/удаляет класс has-focus динамически.

@Directive({
    selector: "[tabindex]"
})
export class TabindexDirective {
    constructor(private elementHost: ElementRef) {}

    @HostListener("focus")
    setInputFocus(): void {
        this.elementHost.nativeElement.classList.add("has-focus");
    }

    @HostListener("blur")
    setInputFocusOut(): void {
        this.elementHost.nativeElement.classList.remove("has-focus");
    }
}

Ответ 4

Решение заключается в следующем:

  <input (click)="focusOut()" type="text" matInput [formControl]="inputControl"
  [matAutocomplete]="auto">
   <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn" >
     <mat-option (onSelectionChange)="submitValue($event)" *ngFor="let option of 
      options | async" [value]="option">
      {{option.name | translate}}
     </mat-option>
  </mat-autocomplete>

TS
focusOut() {
this.inputControl.disable();
this.inputControl.enable();
}

Ответ 5

<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">

у меня работает от Pardeep Jain