gpt4 book ai didi

javascript - 如何将 FormControl 从模板传递给函数?

转载 作者:行者123 更新时间:2023-12-03 10:02:29 26 4
gpt4 key购买 nike

假设我有这个:

<input formControlName="someName" (click)="onClick()">

我想要我的 onClick函数是通用的并设置相应的值 FormControl (我点击的那个)。

如何通过有关 FormControl作为 onClick 的参数?

我以为我可以从 control 中检索它 FormControlDirective 的属性(property)或 FormControlName但他们都没有 exportAs属性。

最佳答案

我认为这是您想要实现的目标。

import { Directive, HostListener, Optional, Output, EventEmitter } from '@angular/core';
import { NgControl, FormControl } from '@angular/forms';

@Directive({
selector: '[appOnClickControl]' // if you want to target specific form control then use custom selector else you use can use input:
// selector: 'input' to target all input elements
})
export class TestDirective {
@Output() emitFormControl = new EventEmitter<FormControl>();

constructor(@Optional() private formControl: NgControl) {
}


/**
* If your only goal is to set value to the form control then use this
*/
@HostListener('click')
onClick() {
if (this.formControl) {
this.formControl.control.setValue('test');
}
}

/**
* If you wanna pass the form control through the function you might use this
*/
@HostListener('click')
getFormControl(): void {
this.emitFormControl.emit(this.formControl.control as FormControl);
}
}
 <input
appOnClickControl // use this to initialize directive
(emitFormControl)="yourMethod($event)" // $event is the clicked form control
formControlName="test"
></input>

关于javascript - 如何将 FormControl 从模板传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60745797/

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