简体   繁体   中英

How to use reactive form's formControlName with a custom component in Angular

I'm creating a simple Reactive form in Angular. There is already this question and is marked duplicate.

But mine is different. In my case I've a custom component on which I want to use formControlName . Though the form is working correctly but there is an error on console. Please tell me how to fix this.

HTML

<form [formGroup]="myReactiveform" (ngSubmit)="submitForm()">
  <my-file-uploader
    formControlName="attatchmentControl">
  </my-file-uploader>
  <button type="submit">Submit</button>
</form>

TS

myReactiveform: FormGroup;

ngOnInit(): void {
  this.myReactiveform= new FormGroup({
    attatchmentControl: new FormControl('', [])
  });
  submitForm() {
    ...
  }
}

my-file-uploader.component.html

<input type="file" single>

Error

ERROR Error: No value accessor for form control with name: 'attatchmentControl' at _throwError (forms.js:2574:1) at setUpControl (forms.js:2394:1) at FormGroupDirective.addControl (forms.js:5626:1) at FormControlName._setUpControl (forms.js:6177:1) at FormControlName.ngOnChanges (forms.js:6122:1) at FormControlName.rememberChangeHistoryAndInvokeOnChangesHook (core.js:1471:1) at callHook (core.js:2490:1) at callHooks (core.js:2457:1) at executeInitAndCheckHooks (core.js:2408:1) at selectIndexInternal (core.js:8194:1)

Your custom component must implement ControlValueAccessor interface

In the @Component directive add:

  providers: [{
    provide: NG_VALUE_ACCESSOR,
    multi: true,
    useExisting: MyFileUploaderComponent // your component class name
  }]

Then in the component implement the interface (for example):

export class MyFileUploaderComponent implements ControlValueAccessor {

  control = new FormControl();

  onChange(event) {
    this.onTouched();
  }

  onTouched() {
  }

  writeValue(obj: any): void {
    this.control.setValue(obj);
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  setDisabledState?(isDisabled: boolean): void {
    if (isDisabled) {
      this.control.disable();
    } else {
      this.control.enable();
    }
  }
}

A few more notes:

  • you should initialize the form at the class level (when you define variable) or in the constructor, not in ngOnInit .

  • move submitForm() to class level unless that's a typo or bad copy/paste.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM