Angular 2를 사용한 HTML5 이벤트 처리 (onfocus 및 onfocusout) angular2 지시문 사용을 도울 수 있습니까? <input

날짜 필드가 있고 기본적으로 자리 표시자를 제거하고 싶습니다.

자리 표시자를 제거하기 위해 자바 스크립트 onfocusonfocusout이벤트를 사용 하고 있습니다.

누구든지 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);
      }
  }



답변

사용하려고 (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

최신 정보

각도에서 다른 이벤트를 사용할 수 있습니다.

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


답변

구성 요소의 모든 입력에서 동적으로 포커스 이벤트를 포착하려면 다음을 수행하십시오.

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


답변

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");
    }
}


답변

해결책은 다음과 같습니다.

  <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();
}


답변

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

Pardeep Jain에서 나를 위해 일합니다.


답변