我使用的是 angular 7。我有如下 Stackblitz 所示的父组件和子组件。但是,我正在从子组件中提供 formControlName
。当我写“id”而不是 formControlName
时,一切正常。但是,当我编写 formControlName
时,它给了我错误 No value accessor for form control with name: 'brand'
我把从其他帖子看到的这段代码添加到app.module.ts中来解决,但是没有用。
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => MyChildComponentComponent),
}
]
最佳答案
让您的应用组件像:
<app-my-child-component formControlName="brand"></app-my-child-component>
在组件中而不是在模块中添加提供者,并在那里实现“ControlValueAccessor”方法。
@Component({
selector: 'app-my-child-component',
templateUrl: './my-child-component.component.html',
styleUrls: ['./my-child-component.component.css'],
providers:
[ {
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => MyChildComponentComponent),
}],
})
export class MyChildComponentComponent implements ControlValueAccessor {
value: string;
onChange() {}
onTouched() {}
isDisabled: boolean = false;
writeValue(value) {
this.value = value
}
registerOnChange(fn) {
this.onChange = fn
}
registerOnTouched(fn) {
this.onTouched = fn
}
setDisabledState(isDisabled) {
this.isDisabled = isDisabled;
}
}
在子组件
中不需要另一种形式,它将是这样的:
<input
[value]="value"
(input)="onChange($event.target.value)"
(blur)="onTouched()"
[disabled]="isDisabled"
type="text">
在这里查看堆栈 Blitz :https://stackblitz.com/edit/angular-formgroup-ccj26w?file=src%2Fapp%2Fmy-child-component%2Fmy-child-component.component.ts
关于angular - Angular 7 中名称错误的表单控件没有值访问器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55726709/