Reputation: 145
I am using ionic 4 and creating edit form. I want to show selected option in select box. I have used patch value but its not working. This is my code
Form
<ion-item no-padding>
<ion-label position="floating">Category</ion-label>
<ion-select interface="action-sheet" [formControl]="formObj.controls['item_category']" >
<ion-select-option *ngFor="let category of categories" value="{{category.c_id}}">{{category.c_title}}</ion-select-option>
</ion-select>
</ion-item>
.ts
categories : any = [{"c_id":1,"c_title":"Phone"},
{"c_id":2,"c_title":"jewelry"}];
constructor(private formBuilder: FormBuilder){
this.formObj = formBuilder.group({
item_category: ['', Validators.compose([Validators.required])]
});
this.formObj.patchValue({
item_category: 2,
});
}
Upvotes: 0
Views: 2177
Reputation: 19
html
<ion-item no-padding>
<ion-label>Category</ion-label>
<ion-select interface="action-sheet" [formControl]="formObj.controls['item_category']" [compareWith]="compareFn">
<ion-select-option *ngFor="let category of categories" [value]="category">{{category.c_title}}</ion-select-option>
</ion-select>
</ion-item>
ts
compareFn(e1: any, e2: any): boolean {
return e1 && e2 ? e1.c_id == e2.c_id : e1 == e2;
}
categories : any = [{"c_id":1,"c_title":"Phone"},
{"c_id":2,"c_title":"jewelry"}];
constructor(private formBuilder: FormBuilder){
this.formObj = formBuilder.group({
item_category: ['', Validators.compose([Validators.required])]
});
this.categories.forEach(element => {
if(element.c_id == 2) {
this.formObj.controls['item_category'].patchValue(
element
)
}
});
}
Upvotes: 0
Reputation: 4782
<ion-content>
<form [formGroup]="myform">
<ion-item no-padding>
<ion-label position="floating">Category</ion-label>
<ion-select interface="action-sheet" formControlName="item_category">
<ion-select-option *ngFor="let category of categories" value="{{category.c_id}}">{{category.c_title}}</ion-select-option>
</ion-select>
</ion-item>
</form>
{{myform.value | json}}
</ion-content>
export class HomePage {
myform;
categories = [
{
c_id: 1,
c_title: 'Category 1'
}, {
c_id: 2,
c_title: 'Category 2'
}
];
constructor(public loadingCtrl: LoadingController) {
this.myform = new FormGroup({
item_category: new FormControl()
});
this.myform.patchValue({
item_category: '2',
});
}
}
Upvotes: 3
Reputation: 7059
Just use [(ngModel)]
to bind the actual value property with ion-select
.
<ion-select interface="action-sheet" [(ngModel)]="selectedCategoryId" >
<ion-select-option *ngFor="let category of categories" value="{{category.c_id}}">{{category.c_title}}</ion-select-option>
</ion-select>
ExampleComponent.ts
export class ExampleComponent {
selectedCategoryId= 11;
}
Upvotes: 0