gpt4 book ai didi

angular - 如何消除对 Angular 输入的关注?

转载 作者:行者123 更新时间:2023-12-02 04:28:14 26 4
gpt4 key购买 nike

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

我无法使用 clearfocus() 方法聚焦。我试过这样。

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

最佳答案

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

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

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>

关于angular - 如何消除对 Angular 输入的关注?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51537742/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com