I
I
Ivan Stroykin2017-02-06 17:13:29
Angular
Ivan Stroykin, 2017-02-06 17:13:29

How to pass selected value from custom dropdown list of child component to formGroup?

Good day,
There is a form inside which there are several different shared selectors (components). I understood how to work with child components by binding them to FormGroup. Here is an example of a mini-implementation: link
But the bottom line is that I have these child components as custom drop-down lists ( select2 plugin ). Who can tell how you can pass the FormGroup value?
In the select2 directive itself, I display the value:
@Output() onChange = new EventEmitter();
And simply using: (onChange)="setSelect($event)" I can get the correct selected value in the setSelect() method

<select select2 class="select2" (onChange)="setSelect($event)" formControlName="test3">
...

But I haven't figured out how to pass the formGroup value yet

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ivan Stroykin, 2017-06-30
@StivinKing

Maybe someone will come in handy.

Decision
import { Component, Input } from "@angular/core";
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from "@angular/forms";

@Component({
  selector: 'test-input',
  template: `<input type="text" [(ngModel)]="value" (blur)="onBlur()">`,
  providers: [{provide: NG_VALUE_ACCESSOR, useExisting:TestInputComponent, multi: true}],
})
export class TestInputComponent implements ControlValueAccessor {
  private innerValue: any = '';
  private onTouchedCallback: () => void = () => {};
  private onChangeCallback: (_: any) => void = () => {};

  get value(): any { return this.innerValue; };

  set value(v: any) {
        if (v !== this.innerValue) {
            this.innerValue = v;
            this.onChangeCallback(v);
        }
    }

  onBlur() { this.onTouchedCallback(); }

  writeValue(value: any) {
        if (value !== this.innerValue)
            this.innerValue = value;
    }

  registerOnChange(fn: any) { this.onChangeCallback = fn; }
  registerOnTouched(fn: any) { this.onTouchedCallback = fn; }

  // ... Другие любые действия которые нам нужны

}

Naturally, instead of a simple input, we do whatever we want, the main thing is that the value for the form leaves the basic components of the form like input, select, and others. Later,
in the form, we use this:
<form [formGroup]="form">
  <test-input  formControlName="test"></test-input>
</form>

_
_ _, 2017-02-06
@AMar4enko

blog.rangle.io/angular-2-ngmodel-and-custom-form-c...

G
Gorovalo, 2017-02-09
@Gorovalo

import { FormGroup, FormBuilder } from '@angular/forms';

@Component({
...
})
export class ComponentName {
form: FormGroup;
  
constructor(
    private fb: FormBuilder
  ){
   this.form = this.fb.group({
    test3: [...]
});
}
}

setSelect(event) {
  this.form.controls['test3'].setValue(event);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question