2017-09-17 57 views
0

我创建了一个plunkr解释什么即时通讯谈论 https://plnkr.co/edit/42Gcd8jayIO3EReiKCLf?p=preview在角4如何失去焦点KEYUP

//our root app component 
import {Component, NgModule, VERSION} from '@angular/core' 
import {BrowserModule} from '@angular/platform-browser' 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <input (keyup.enter)=func() > 
    </div> 
    `, 
}) 
export class App { 
    name:string; 
    constructor() { 
    } 
    func(){ 
    console.log("lose focus here") 
    } 
} 

@NgModule({ 
    imports: [ BrowserModule ], 
    declarations: [ App ], 
    bootstrap: [ App ] 
}) 
export class AppModule {} 

我不想失去焦点输入框上KEYUP

回答

2

你可以失去焦点通过设置$event.target.blur()的按键事件,

<input (keyup.enter)="$event.target.blur()" > 

DEMO

2

有实现你想要什么的多种方式,另一个例子是使用@ViewChild和ElementRef。

HTML:

<input #myEventRef (keyup.enter)="myEvent()" /> 

组件:

import { Component, ElementRef, ViewChild } from "@angular/core"; 


@Component({ 
    selector: "app", 
    templateUrl: "./app.component.html", 
}) 
export class AppComponent { 
    constructor(private readonly el: ElementRef) { 
    } 

    @ViewChild("myEventRef") myEventRef: ElementRef; 

    myEvent() { 
     this.myEventRef.nativeElement.blur(); 
    } 
} 

而且你可以更进一步利用@HostListener,对此我不会显示。