我真的不知道你想要什么。您的自定义表单控件也适用于响应式表单(请参阅 your custom form control using reactive form)
<form [formGroup]="myForm">
<app-elements-input formControlName="name" ...>
</app-elements-input>
</form>
//and
myForm=new FormGroup(
{
name:new FormControl()
}
)
嗯,有时需要知道控件何时无效,触摸...
一种简单的方法是添加为提供者 NG_VALIDATORS
{provide: NG_VALIDATORS,
useExisting:forwardRef(() => InputComponent),
multi: true}
添加一个变量,例如
control:any=null;
e 实现了 Validator,它在声明中添加并创建一个函数 validate 我们为“控制”赋予价值
export class InputComponent implements ...,Validator {..}
public validate(c: FormControl) {
if (!this.control)
this.control=c;
return null;
// return (!this._value && !this.required)?{required:true}:null
}
所以你可以在 html 中使用一些类似的东西
<span *ngIf="control?.invalid">*</span>
不要忘记在控件被触摸时指示,在示例中,我们可以使用输入的事件(模糊)
<input ... (blur)="onTouched()">
如果你想制作一个组件来控制一个表单组,它只能作为 `@Input()' fromGroup 或 formControl 传递
<form [formGroup]="myForm">
<children [argformControl]="myForm.get('name')">
</children>
</form>
//and
@Input() argformControl:FormControl
或
<form [formGroup]="myForm">
<children [argFormGroup]="myForm">
</children>
</form>
//and
@Input() argFormGroup:FormGroup
Update 这允许,例如如果我们有一个对象数组,比如
data=[{name:'name',label:'Name'},{name:'surname',label:'Surname'}]
点赞
<!--I add a "clasic" *ngIf to avoid initialize problems
It can be placed in the form, or in children-->
<form *ngIf="myForm" [formGroup]="myForm">
<children [argFormGroup]="myForm" [data]="data">
</children>
</form>
我们的孩子变成了
<div *ngFor="let item of data">
{{item.label}}<input [formControl]="argFormGroup.get(item.name)">
</div>
//and
@Input() argFormGroup:FormGroup
@Input() data:any[]
自定义 formControl 是一个“黑匣子”。您发送一个值 - 一个字符串,一个对象...... - 您可以修改此字符串或对象。它看起来像一个“复杂的输入”(一个 mat-date-picker,例如是一个自定义表单控件)