我正在我的角9应用程序中实现原子设计。这意味着我将用原子、分子和有机体来构建我的网页。除了ReactiveFormsModule,一切都很好。
我想将<input />转换成它自己的组件,这样我就不必总是重复相关的HTML。然而,反应形式没有任何一种。
下面的示例是返回一个错误onload:ERROR Error: No value accessor for form control with name: 'field2'
我用完整的代码制作了一个StackBlitz示例。
app.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({selector: 'app-root',templateUrl: './app.component.html'})
export class AppComponent {
form: FormGroup;
constructor(fb: FormBuilder) {
this.form = fb.group({
field1: ['value1', [Validators.required]],
field2: ['value2', [Validators.required]],
});
}
onSubmit() {console.log(this.form.value);}
}这里的app.component.html,我尝试用原子替换第二个输入。
<form [formGroup]="form" (ngSubmit)="onSubmit();">
<label>
Field 1 <input formControlName="field1" />
</label>
<label>
Field 2 <app-input formControlName="field2"></app-input>
</label>
<button type="submit">Submit</button>
</form>input.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-input',
template: '<input [formControlName]="formControlName" />',
})
export class InputComponent implements OnInit {
@Input() formControlName: string;
constructor() { }
ngOnInit(): void {
}
}我试图通过ControlValueAccessor实现一个本教程,但这导致了奇怪的行为。
有人能告诉我如何做到这一点吗?
发布于 2020-07-07 11:06:39
如果你想让你的生活变得简单,那么使用FormControl作为你的自定义组件的输入--这是我的应用程序的代码
// custom component
@Input() set control(value: FormControl) {
if (this._control !== value) {
this._control = value;
}
}
// tempalte
<input [formControl]="_control">输入父控件我不使用formBuilder,而是直接使用fromControl和formGroup。
name = new FormControl('');
constructor(){
let name = this.name;
this.formGroup = new FromGroup({name });
// template
<custom-control [control]="name">问题样本中的最新解决方案:
app.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({selector: 'app-root',templateUrl: './app.component.html'})
export class AppComponent {
form: FormGroup;
constructor(fb: FormBuilder) {
this.form = fb.group({
field1: ['value1', [Validators.required]],
field2: ['value2', [Validators.required]],
});
}
onSubmit() {console.log(this.form.value);}
}app.component.html
<form [formGroup]="form" (ngSubmit)="onSubmit();">
<label>
Field 1 <input formControlName="field1" />
</label>
<label>
Field 2 <app-input [control]="form.controls.field2"></app-input>
</label>
<button type="submit">Submit</button>
</form>input.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-input',
template: '<input [formControl]="formControl" />',
})
export class InputComponent implements OnInit {
@Input() set control(value: FormControl) {
if (this.formControl !== value) {
this.formControl = value;
}
}
formControl: FormControl;
constructor() { }
ngOnInit(): void { }
}https://stackoverflow.com/questions/62773481
复制相似问题