Answer the question
In order to leave comments, you need to log in
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">
...
Answer the question
In order to leave comments, you need to log in
Maybe someone will come in handy.
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; }
// ... Другие любые действия которые нам нужны
}
<form [formGroup]="form">
<test-input formControlName="test"></test-input>
</form>
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 questionAsk a Question
731 491 924 answers to any question