2021年2月6日星期六

Angular set selected option value in dropdown list in edit form

in angular and asp.net application, I have an edit form in my component with multiple select options in dropdown list, where display all data in edit form except dropdown list fields is displayed as empty with all dropdown list values not with formerly stored dropdown list value. So I need to set the selected option value in the dropdown list when i go to the edit form in edit.component.html.

this is 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"></option>  </select>
https://stackoverflow.com/questions/66083889/angular-set-selected-option-value-in-dropdown-list-in-edit-form February 07, 2021 at 10:02AM

没有评论:

发表评论