Xử lý sự kiện HTML5 (onfocus và onfocusout) sử dụng góc 2


118

Tôi có trường ngày tháng và tôi muốn xóa trình giữ chỗ theo mặc định.

Tôi đang sử dụng javascript onfocusonfocusoutcác sự kiện để xóa trình giữ chỗ.

Bất cứ ai có thể giúp đỡ với việc sử dụng chỉ thị angle2?

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

Tôi cố gắng giải quyết theo cách này, nhưng tôi gặp sự cố khi đặt lại loại trường nhập.

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

Câu trả lời:


235

Cố gắng sử dụng (focus)(focusout)thay vì onfocusonfocusout

như thế này : -

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

bạn cũng có thể sử dụng như thế này: -

một số người thích thay thế tiền tố on-, được gọi là biểu mẫu chuẩn:

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

Biết thêm về ràng buộc sự kiện xem tại đây .

bạn phải sử dụng HostListner cho trường hợp sử dụng của mình

Angular sẽ gọi phương thức được trang trí khi phần tử chủ phát ra sự kiện được chỉ định. @HostListenerlà trình trang trí cho phương thức xử lý sự kiện / gọi lại

Xem Cập nhật của tôi Plunker hoạt động.

Ví dụ làm việc Working Plunker

Cập nhật

Một số sự kiện khác có thể được sử dụng trong góc -

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

nơi bạn đã sử dụng chỉ thị của bạn có tên là dateinput?
Pardeep Jain

@vishnu xem plnuker cập nhật của tôi
Pardeep Jain

2
Một điều cần lưu ý, nếu bạn sử dụng triển khai HTML mặc định, nó có thể sử dụng phạm vi toàn cục khi gọi hàm được chỉ định. Ví dụ:, onfocusout="someMethod()" someMethod()trong trường hợp này, sẽ được gọi trong phạm vi toàn cục. Đó là một lý do khác tại sao việc sử dụng Angular trong trường hợp này lại có giá trị.
kbpontius

1
@ user5365075 Tôi không thấy bất kỳ bản cập nhật như vậy, xem tại đây ng6 bản demo sử dụng focus stackblitz.com/edit/...
Pardeep Jain

2
Sai lầm của tôi, focussẽ làm việc trên các đầu vào được hỗ trợ và textareas, nhưng nếu bạn có thành phần tùy chỉnh mà không hỗ trợ nó, bạn có thể sử dụng focusinthay vì :)
user5365075

7

Nếu bạn muốn bắt sự kiện tiêu điểm một cách động trên mọi đầu vào trên thành phần của mình:

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

Kiểm tra mã đầy đủ tại đây: https://stackblitz.com/edit/angular-93jdir


2

Tôi đã tạo một chỉ thị nhỏ liên kết với thuộc tính tabindex. Nó thêm / xóa động lớp 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

Giải pháp là:

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

làm việc cho tôi từ Pardeep Jain

Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.