【问题标题】:No value accessor for form control with name error in angular 7Angular 7 中没有名称错误的表单控件的值访问器
【发布时间】:2019-04-17 20:22:25
【问题描述】:

我正在使用 Angular 7。我有父子组件,如下面的 Stackblitz。但是,我从子组件中提供formControlName。当我写“id”而不是formControlName 时,一切正常。但是,当我写formControlName 时,它给了我错误No value accessor for form control with name: 'brand'

STACKBLITZ

我将在其他帖子中看到的这段代码添加到 app.module.ts 以解决问题,但它不起作用。

providers: [
  { 
    provide: NG_VALUE_ACCESSOR,
    multi: true,
    useExisting: forwardRef(() => MyChildComponentComponent),
  }
]

【问题讨论】:

  • 这不是重复的。我应用了该问题中接受的解决方案。但是,它对我不起作用。我的问题不一样。 @PrashantPimpale

标签: angular typescript angular7


【解决方案1】:

让你的应用组件像:

<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;
  }

}

child component 不需要其他形式,它会是这样的:

<input 
  [value]="value"
  (input)="onChange($event.target.value)"
  (blur)="onTouched()"
  [disabled]="isDisabled"
  type="text">

在这里查看堆栈闪电战:https://stackblitz.com/edit/angular-formgroup-ccj26w?file=src%2Fapp%2Fmy-child-component%2Fmy-child-component.component.ts

【讨论】:

  • 非常感谢@xyz。有效。我的错误是添加到app.module.ts。但是,正确的地方是child-component.ts
  • @realist 第二个输入是什么?在此处查看示例:stackblitz.com/edit/…
  • @realist 实现控制值访问器、注册函数、setDisabledState 等所有方法。这样你就可以实现响应式表单的所有功能
  • 我看了你的 stackblitz。而且我现在了解到,到目前为止,我总是用错误的方式。非常感谢。你照亮了我。
  • @realist:如前所述,您必须注册功能,现在检查我的编辑,打开答案中的stackblitz。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-03
  • 1970-01-01
  • 2020-07-16
  • 1970-01-01
  • 1970-01-01
  • 2018-03-24
相关资源
最近更新 更多