【发布时间】:2021-02-12 05:29:57
【问题描述】:
所以,我正在尝试创建一个自定义组件,以便在整个应用程序中、在表单内或作为独立组件使用。这是我目前所拥有的。
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>
现在到父组件 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>
结果:
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
问题:我在 “事件” 中得到了正确的选择,但是在提交表单时,我得到的选项列表中所选值的位置不是实际值。
如何根据 controlName 将事件传递给表单本身?
【问题讨论】:
标签: angular angular-components angular-forms custom-component