So, I'm trying to create a custom component to be used across the application, inside a form or as a standalone. here's what I have so far.
custom-select.ts
@Component({
selector: 'app-custom-select',
templateUrl: './custom-select.component.html',
styleUrls: ['./custom-select.component.scss'],
viewProviders: [{
provide: ControlContainer,
useExisting: FormGroupDirective
}]
})
export class CustomSelectComponent implements OnInit {
@Input()
public selection: any[] = [];
@Input()
public controlName: string;
@Output()
selectionChange: EventEmitter<any> = new EvenEmitter<an>();
constructor() {}
ngOnInit() { //sort option list and do other stuff }
onSelectionChange(event) {
this.selectionChange.emit(event)
}
}
custom-select.html
<ng-select>
[items]="selection"
bindValue= "id"
bindLabel="label"
[formControlName]="controlName"
(change)="onSelectionChange($event)"
</ng-select>
now to the parent component app-component.ts
export class appComponent implements OnInit {
testForm: FormGroup = new FormGroup({
City: new FormControl(null),
State: new FormControl(null)
});
cities: any[] = [];
states: any[] = [];
constructor() {}
ngOnInit() { // populate cities & states}
.....
.....
onSubmit() {
console.log("Form Values", this.testFrom.value);
}
testCity(event) { console.log("City: ", event); }
testState(event) { console.log("State: ", event); }
}
app-component.html
<form [ngForm]="testForm">
<custom-select
[selection]="cities"
controlName="City"
(onSelectionChange)="testCity($event)"
></custom-select>
<custom-select
[selection]="states"
controlName="State"
(onSelectionChange)="testState($event)"
></custom-select>
</form>
Results:
City: {id: 101, label: "Chicago"} //correct value
State: {id: 20, label: "Illinois"} //correct value
FormValues: {City: 3, State: 1} //needs to hold above objects instead of list position of selected items
Problem: I'm getting the correct selection inside the "event", but on form submission I'm getting the position of the selected value in options list not the actual values.
How do I achieve passing the event to the form itself depending on the controlName?