如何消除对角输入的关注?

时间:2018-07-26 11:28:39

标签: angular

是否有任何方法或方法可以消除对Angular输入字段的关注?

我无法使用clearfocus()方法进行对焦。我已经尝试过这种方法。

@ViewChild("textbox1") el: ElementRef;
this.el.nativeElement.clearFocus();

1 个答案:

答案 0 :(得分:0)

这是解决此问题的一种方法,同时避免将表示逻辑放入组件代码中。

我的解决方案涉及一个自定义指令:

import { Directive, Input, ElementRef, EventEmitter, OnDestroy } from "@angular/core";
import { Subscription } from 'rxjs';

@Directive({
    selector: "[blurOn]"
})
export class BlurOnDirective implements OnDestroy {

    private _attachedEvent: EventEmitter<void> | null = null;
    private _eventSubscription: Subscription | null = null;

    public constructor(private readonly _element: ElementRef) {
    }

    public ngOnDestroy(): void {
        if (this._eventSubscription)
            this._eventSubscription.unsubscribe();
    }

    @Input("blurOn")
    public set attachedEvent(value: EventEmitter<void> | null) {
        if (this._attachedEvent === value) 
            return;

        if (this._eventSubscription)
            this._eventSubscription.unsubscribe();
        this._attachedEvent = value;
        if (value)
            this._eventSubscription = value.subscribe(() => this.onEvent());
    }

    private onEvent(): void {
        const nativeElement: any = this._element.nativeElement;
        if (typeof(nativeElement.blur) === "function")
            nativeElement.blur();
    }

}

向组件添加事件

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

@Component({
    ...
})
export class YourComponent {

    public readonly submittedValue: EventEmitter<void>;

    public submitValue(): void {
        this.submittedValue.emit();
    }

}

将View与ViewModel逻辑松散耦合:

<input [blurOn]="submittedValue"></input>