Angular 2を使用したHTML5イベント処理(onfocusおよびonfocusout)


118

日付フィールドがあり、デフォルトでプレースホルダーを削除したい。

プレースホルダーを削除するためにJavaScript 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);
      }
  }

回答:


235

(focus)andの(focusout)代わりにonfocusand を使用してみてくださいonfocusout

このような : -

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

また、次のように使用できます:-

一部の人々は、正規形として知られている接頭辞の代替を好みます:

<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()"

次の名前のディレクティブをどこで使用しましたdateinputか?
Pardeep Jain、

@vishnu更新されたplnukerを参照
Pardeep Jain

2
注意すべき点として、デフォルトのHTML実装を使用すると、指定された関数を呼び出すときにグローバルスコープが使用されることがあります。例:onfocusout="someMethod()" someMethod()この場合、はグローバルスコープで呼び出されます。これが、この場合にAngularを使用することが重要であるもう1つの理由です。
kbpontius 2017年

1
@ user5365075そのような更新はありませんでした。ここで、stackblitz.com focus / edit

2
私の間違いは、focusサポートされている入力とテキスト領域で動作しますが、サポートしていないカスタムコンポーネントがある場合は、focusin代わりに使用できます:)
user5365075

7

コンポーネントのすべての入力でフォーカスイベントを動的にキャッチする場合:

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


2

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

0

解決策はこれです:

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

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

Pardeep Jainの作品

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.