angular - Angular 7 中名称错误的表单控件没有值访问器

标签 angular typescript angular7

我使用的是 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),
  }
]

最佳答案

让您的应用组件像:

<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/

相关文章:

node.js - 使用 angular2 应用程序发送的 Express.js 接收 POST 数据

angular - 在 DragulaService.setOptions 中访问 this 的值

javascript - 如何在没有按钮的情况下访问浏览器? ( ionic 3)

angular - 分页、排序和过滤器不适用于 Angular Material 项目

angular - 错误 : Can't resolve all parameters for Location: (? ) 在 angular7 webpack 应用程序中

javascript - Angular 5 - 如何在用户点击目标元素外部时触发事件

javascript - 动态更新 Angular2 指令中自定义属性的值

reactjs - React-Redux 应用程序中的不变性 - Immutablejs 和 Typescript 冲突

javascript - 是否可以使用 typescript 映射类型来创建接口(interface)的非函数属性类型?

angular - 为 Angular 应用程序缓存 Assets 文件夹中的静态文件(图像、pdf、png 等)?