简体   繁体   English

如何将 FormControl 传递给模板中的函数?

[英]How can I pass a FormControl to a function from the template?

Let's say I have this:假设我有这个:

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

I want my onClick function to be generic and set the value of the corresponding FormControl (the one I clicked).我希望我的onClick函数是通用的,并设置相应FormControl (我单击的那个)的值。

How can I pass the concerned FormControl as a parameter of onClick ?如何将相关FormControl作为onClick的参数传递?

I thought I could retrieve it from the control property of FormControlDirective or FormControlName but none of them have an exportAs attribute.我以为我可以从FormControlDirectiveFormControlNamecontrol属性中检索它,但它们都没有exportAs属性。

I think this is what you want to achieve.我认为这就是您想要实现的目标。

 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>

In your html:在你的 html 中:

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

And then define your onClick function as:然后将您的 onClick 函数定义为:

onClick(event): void {
 alert(event.target.value)
}

Edit To get FormControl:编辑以获取 FormControl:

<input formControlName="someName" (click)="onClick(Form.get('someName'))">

and

onClick(formControl): void {
    formControl.setValue(someValue);
  }

kinda repetitive but pretty sure you can only do this:有点重复,但很确定你只能这样做:

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

then use someName on your form group to find the control然后在您的表单组上使用 someName 来查找控件

onClick(name: string) {
  const fc = this.form.get(name);
  // do whatever
}

Not exactly sure what you're after, but try if the following works for you.不完全确定您在追求什么,但请尝试以下方法是否适合您。 It uses setValue() method to set values for the form.它使用setValue()方法为表单设置值。 You can also use patchvalue if you want to set only partial values of the form.如果您只想设置表单的部分值,您也可以使用patchvalue

Template模板

<form [formGroup]='groupedform' >
  <label>Name:  <br>
    <input type="text" formControlName='Name' required (mousedown)="onMouseDown(groupedform)"/>
  </label>
  <br>
  <br>
  <label>Email:  <br>
    <input type="email" formControlName='Email' required (mousedown)="setEmail(groupedform)"/>
  </label>
  <p>
  <button type="submit" [disabled]="!groupedform.valid" (click)="updateName()">Update Name</button>
  </p>
</form>

Component成分

export class AppComponent  {
   name = 'Angular';
   firstname = new FormControl('');
   groupedform = this.fb.group({
    Name : ['', Validators.required],
    Email: [],
  });

  constructor(private fb:FormBuilder) { }

  updateName() {
    console.log(this.groupedform.value);
  }

  onMouseDown(formControl: any) {
    this.groupedform.setValue({
      'Name': 'sample',
      'Email': 'sample@example.com'
    });
  }

  setEmail(formControl: any) {
    this.groupedform.patchValue({
      'Email': 'sample@example.com'
    });
  }
}

Working example: Stackblitz工作示例: Stackblitz

You can use template variable for this您可以为此使用模板变量

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

onClick(val) {
console.log(val);}

I am not sure what type of value you want to set, but you can use an attribute directive for this type of common operation (if it is simple).我不确定您要设置什么类型的值,但是您可以对此类常见操作使用属性指令(如果它很简单)。

You can create an attribute directive and set on all the form controls, the attribute directive logic will automatically handle it for you.您可以创建一个属性指令并在所有表单控件上进行设置,属性指令逻辑会自动为您处理。 You can definetely configure the values passed to directives.您可以明确地配置传递给指令的值。

import { Directive, HostListener, ElementRef, Input } from "@angular/core"; import { Directive, HostListener, ElementRef, Input } from "@angular/core";

@Directive({
  selector: '[clickMe]'
})
export class ClickDirective {
  @Input('clickMe') clickValue:string;
  constructor(private elementRef: ElementRef){}

  @HostListener('click') onClick() {
    this.elementRef.nativeElement.value = this.clickValue;
  }
}

Now just use these directives with the the form controls and pass your values, you can use data binding as well.现在只需将这些指令与表单控件一起使用并传递您的值,您也可以使用数据绑定。

<form [formControl]="myForm">
  Firstname:<input type="text" fromControlName="firstname" [clickMe]="'first value'" />
<br>
Lastname:<input type="text" fromControlName="lastname" [clickMe]="'last value'" />
</form>

Please find the working stackblitz here: https://stackblitz.com/edit/angular-j1kwch请在此处找到有效的 stackblitz: https ://stackblitz.com/edit/angular-j1kwch

You could use the event passed and get the attribute name out of it:您可以使用传递的事件并从中获取属性名称:

<input type="text" class="form-control" formControlName="yourName" (blur)="yourMethod($event)" />

Then in your method get the name of the formControlName from the target:然后在您的方法中从目标获取formControlName的名称:

yourMethod(event: any) {
  const controlName = e.target.getAttribute('formcontrolname');
  this.formGroup.get(controlName); // this is your FormControl
  ....
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 Javascript 设置 Angular formcontrol 字段的值? - How can I set the value of an Angular formcontrol field from Javascript? 如何在Backbone.js中将自定义功能从路由器,视图传递到模板? - How can I Pass a Custom function from Router, to View, to Template in Backbone.js? 我如何将数据从Django模板传递到Angle 4? - How can i pass data from django template to angular 4? 如何在模板中将数据从 Flask 传递到 JavaScript? - How can I pass data from Flask to JavaScript in a template? 如何将模板中的值传递给 ts function - How to pass a value from template to ts function 如何将索引从过滤器函数传递到映射函数? - How can I pass the index from the filter function into the map function? 如何通过单击 Reactjs 中的按钮将 FormControl 从禁用切换为启用 - How can I toggle a FormControl from disabled to enabled with a button click in Reactjs 如何将变量从一个函数传递给另一个函数? - How can I pass a variable from one function to another? 如何将结果从 javascript 传递给 laravel 函数作为数量? - How can I pass RESULT from javascript to laravel function as amount? 如何在组件中传递来自 vue function 的参数? - How can i pass parametres from vue function in component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM