In my Angular and ASP.NET application, I have an edit form in a component with multiple select options in a dropdown list. When displaying all data in the edit form, the dropdown list fields are displayed as empty instead of showing the previously stored values. I need to set the selected option value in the dropdown list when navigating to the edit form in edit.component.html. Here is the code in my edit.component.ts:
id: number;
userForm: FormGroup;
Charity: Charities;
Charities: Charities[];
users: Users[];
Cities: City[];
Categories: Category[];
selected: any;
Regions: Region[];
constructor(private activateRoute: ActivatedRoute,private route: Router,private fb : FormBuilder, private CharityService : CharityService,private toastr: ToastrService , private RegisterService : AccountService, private router : ActivatedRoute) { }
ngOnInit(): void {
var userId = this.router.snapshot.params['id'];
this.setForm(userId);
this.CharityService.GetAllCategories().then(res => this.Categories = res as Category[])
this.CharityService.GetAllRegions().then(res => this.Regions = res as Region[])
this.CharityService.GetAllUsers().then(res => this.users = res as Users[]);
this.users = [];
}
get editFormData() { return this.userForm.controls; }
private setForm(id:number) {
this.CharityService.GetCharit(id).then(x => {
this.Charity = x;
this.userForm = this.fb.group({
id: [this.Charity.id, [Validators.required]],
name: [this.Charity.name, [Validators.required]],
phone: [this.Charity.phone, [Validators.required]],
SubCategoryId: [this.Charity.SubCategoryId, [Validators.required]],
RegionId: [this.Charity.RegionId, [Validators.required]],
CityId: [this.Charity.CityId, [Validators.required]],
Category:[this.Charity.Category, [Validators.required]],
});
});
}
This is edit.component.html:
For example, formControlName="SubCategoryId"
<select class="custom-select" [(ngModel)]="Categories" formControlName="SubCategoryId" [ngClass]="{'is-invalid' :!this.userForm.get('SubCategoryId').valid && this.userForm.get('SubCategoryId').touched}" [(value)]="selected" required>
<option selected value="" disabled class="dove">اختر التصنيف</option>
<option *ngFor="let cat of Categories" [value]="cat.id">{{cat.subCategoryName}}</option>
</select>
Can anyone help me?