M
M
microf2018-05-13 22:21:58
Angular
microf, 2018-05-13 22:21:58

How to implement ControlValueAccessor?

I asked the question How to pass the FormControlName to the component and the respected denismaster answered me there, what should be implemented ControlValueAccessorand yes. I read about it and yes, I’m very ashamed, but I didn’t understand a damn thing how to transfer parameters through it to the
Stackblitz component

<form [formGroup]="SignupReactiveForm">
        <div class="form-group">
            <app-input  label="email" type="email" formControlName="email">
</app-input></div>
</form>

In SignupComponent, I implemented a form where I connect my own component
<app-input  label="email" type="email" formControlName="email">

Okay, in the component InputComponentI connect ControlValueAccessor, I somehow implement this interface
writeValue(value: any) {
   this.formControlName = value;
  }
  registerOnChange() { }
  registerOnTouched() { }

, I register it
{
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => InputComponent),
      multi: true
    }

and how then? How do I get writeValuethe formControlName value and how do I output it???
stackblitz

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Arthur, 2018-06-09
@antoart

Hello.
I will rely on your own code.
The implementation of this interface allows the Angular form to interact with the custom component. The method

writeValue(value: any) {
   this.formControlName = value;
  }

that value which you transfer in formControlName is thrown. Note that this is not a Binding like between components. In order for the value to be transferred, it is necessary to say to the form directly and specifically
form.setValue({email: "email", password: 'passworddd'})
// или 
form.patchValue({email: "email"})

And in order to dynamically read the value that you pass through the this.propagateChange(val) function, you must already work with the form change
this.filterForm.valueChanges
      .pipe(
        takeUntil(this._onDestroy$)
      )
      .subscribe((val) => {
       console.log(val);
      });

And you understand what you want. Throw parameters into the component (binding) or throw the form value into the component (ControlValueAccessor).
ps write in your code, and see how the form values ​​​​from the already child component fall into the console.
initForm() {
    this.SignupReactiveForm = this.fb.group({
      password: ['password', [
        Validators.required,
        Validators.pattern(/[A-z]/)
      ]
      ],
      email: ['email', [
        Validators.required, Validators.email
      ]
      ],
      

    });
  }

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question