将 formControlName 传递给 Angular 组件
[英] Passing formControlName into Angular component
本文介绍了将 formControlName 传递给 Angular 组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个反应形式.设置与此类似:
myForm: FormGroup;this.myForm= new FormGroup({名称:new FormControl("", [Validators.required, Validators.maxLength(15), Validators.pattern('...')]),...});
我像这样在表单上使用它:
<输入类型=文本"表单控件名称=名称"/><div *ngIf="name.errors?.required">姓名为必填项
<div *ngIf="name.errors?.maxlength">名称必须是 {{ name.errors.maxlength.requiredLength }} 个字符
<div *ngIf="name.errors?.pattern">名称包含无效字符.
这只是我表格的精简版.我有多个输入,我不得不为每个输入创建错误 div.
为了解决这个问题,我尝试创建一个组件.该组件与上面的代码非常相似:
<输入类型=文本"[formControlName]="formControlName"/><div *ngIf="name.errors?.required">姓名为必填项
等等...
ts 文件:
@Component({选择器:应用文本",templateUrl: './text.component.html'})导出类 TextComponent {@Input() 表单控件名称:表单控件;}
所以在我的表单上,我想按如下方式使用这个组件:
<app-text [formControlName]="name"></app-text>
但我不能让它与 formControlName 属性一起使用.
这可能吗?
谢谢
我快到了.
我已经创建了这个 StackBlitz 来展示我的进步:
演示>
现在正在努力解决这些错误以及如何访问 formControl 以检查这些错误
解决方案
需要将表单控件传递给input元素,
<输入[值]="val"类型=文本"(input)="val=$event.target.value;onChange($event.target.value)"(模糊)="onTouched()"[formControl]="控制"><span *ngIf="control && !control.valid && control.touched"><span class="error" *ngIf="control.errors['required']">该字段不应为空</span><span class="error" *ngIf="control.errors['email']">该字段应该是电子邮件</span></span>
获取自定义组件中的控件作为输入并基于此显示错误.
import { Component, OnInit, forwardRef, Input, OnChanges } from '@angular/core';从@angular/forms"导入 { FormControl, ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS };@成分({选择器:应用测试",templateUrl: './test.component.html',styleUrls: ['./test.component.css'],供应商: [{ 提供:NG_VALUE_ACCESSOR,useExisting:forwardRef(() => TestComponent),multi:true }]})导出类 TestComponent 实现 ControlValueAccessor、OnChanges {构造函数(){}传播变化:任何=()=>{};@Input() 控件:FormControl;@Input('messageValue') _messageValue = 'whateves';获取消息值(){返回 this._messageValue;}设置消息值(val){console.log('设置消息值', val)this._messageValue = val;this.propagateChange(val);}嗨(事件){console.log('嗨');控制台日志(事件)this.messageValue = 事件;}ngOnInit() {}ngOnChanges(更改){console.log('更改', 更改);this.propagateChange(this.messageValue);}写值(值){console.log('writeValue', value);如果(值){this.messageValue = 值;}}registerOnChange(fn) {console.log('onChange')this.propagateChange = fn;}registerOnTouched() {}}
I have a reactive form. The setup is similar to this:
myForm: FormGroup;
this.myForm= new FormGroup({
name: new FormControl("", [Validators.required, Validators.maxLength(15), Validators.pattern('...')]),
...
});
I use this on my form like this:
<input
type="text"
formControlName="name"
/>
<div *ngIf="name.errors?.required">
Name is required
</div>
<div *ngIf="name.errors?.maxlength">
Name must be {{ name.errors.maxlength.requiredLength }} characters
</div>
<div *ngIf="name.errors?.pattern">
Name has invalid characters.
</div>
This is just a cut down version of my form. I have multiple input and I've had to create the error div's for each input.
So to fix this I've tried to create a component. The component is very similar to the code above:
<input
type="text"
[formControlName]="formControlName"
/>
<div *ngIf="name.errors?.required">
Name is required
</div>
etc...
ts file:
@Component({
selector: 'app-text',
templateUrl: './text.component.html'
})
export class TextComponent {
@Input() formControlName: FormControl;
}
So on my form I'd like to use this component as follows:
<app-text [formControlName]="name"></app-text>
But I can't get this to work with the formControlName property.
Is this possible?
Thanks
I'm nearly there.
I've create this StackBlitz so show my progress:
Demo
Just struggling with the errors now and how to access the formControl to check for those errors
解决方案
You need to pass the form control to the input element ,
<input
[value]="val"
type="text"
(input)="val=$event.target.value;onChange($event.target.value)"
(blur)="onTouched()"
[formControl]="control"
>
<span *ngIf="control && !control.valid && control.touched">
<span class="error" *ngIf="control.errors['required']"> The field should not be empty</span>
<span class="error" *ngIf="control.errors['email']"> The field should be an email
</span>
</span>
Get the control in your custom component as input and show the error based on this.
import { Component, OnInit, forwardRef, Input, OnChanges } from '@angular/core';
import { FormControl, ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS } from '@angular/forms';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css'],
providers: [
{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TestComponent), multi: true }
]
})
export class TestComponent implements ControlValueAccessor, OnChanges {
constructor() { }
propagateChange:any = () => {};
@Input() control: FormControl;
@Input('messageValue') _messageValue = 'whateves';
get messageValue() {
return this._messageValue;
}
set messageValue(val) {
console.log('set messageValue', val)
this._messageValue = val;
this.propagateChange(val);
}
hi(event) {
console.log('hi');
console.log(event)
this.messageValue = event;
}
ngOnInit() {
}
ngOnChanges(changes) {
console.log('changes', changes);
this.propagateChange(this.messageValue);
}
writeValue(value) {
console.log('writeValue', value);
if (value) {
this.messageValue = value;
}
}
registerOnChange(fn) {
console.log('onChange')
this.propagateChange = fn;
}
registerOnTouched() {}
}
这篇关于将 formControlName 传递给 Angular 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!