Home > Enterprise >  Unable to set default selection in select item
Unable to set default selection in select item

Time:08-31

I bring data from the server and try to add a product and give it the appropriate category, I manage to add the product, but in the UI for a start I am not shown the first category Instead, it shows me an empty option and only when I click do all the options appear.

Before:

enter image description here

After:

enter image description here

I want from the beginning to be shown the first option, which is A.

My Code:

Components.ts:

  categories:Category[] = [];
  category!:Category;

  formNewProduct:FormGroup = new FormGroup({});
  constructor(private formBuilder:FormBuilder,private productService:ProductService,
  private router:Router,private alertService:AlertService,public validationService:ValidationService
  ,private categoryService:CategoryService) { }

  ngOnInit(): void {
    this.formNewProduct = this.formBuilder.group({
      name:[''],
      description:[''],
      photoUrl:[''],
      price:[''],
      categoryId:['']
    }) 

    this.getAllCategories();

    this.category = this.categoryService.getCategory();
  }
  
  getAllCategories(){
    this.categoryService.getAllCategories().subscribe((res)=>{
      this.categories = res;
    })
  }

HTML:

<div >
<select  formControlName="categoryId" [(ngModel)]="category.id">
<option *ngFor="let c of categories" [value]="c.id">
{{c.name}}
</option>
</select>
</div>

Service:

  getCategory():Category{
    let categoryString = localStorage.getItem("category");
    let category = new Category;
    if(categoryString){
      category = JSON.parse(categoryString);
    }
    return category;
  }

CodePudding user response:

You need to use patchValue after the dropdown is fetched, then it will populate; and either perform either reactive or template driven validation not both together (not advised but allowed). Here I am populating using reactive forms.

categories: Category[] = [];
category!: Category;

formNewProduct: FormGroup = new FormGroup({});
constructor(
    private formBuilder: FormBuilder,
    private productService: ProductService,
    private router: Router,
    private alertService: AlertService,
    public validationService: ValidationService,
    private categoryService: CategoryService
) {}

ngOnInit(): void {
    this.formNewProduct = this.formBuilder.group({
        name: [''],
        description: [''],
        photoUrl: [''],
        price: [''],
        categoryId: [''], 
    });
    this.getAllCategories();
}

getAllCategories() {
    this.categoryService.getAllCategories().subscribe(res => {
        this.categories = res;
        // this.category = this.categoryService.getCategory(); // not needed for now!
        this.formNewProduct.patchValue({categoryId: res[0].id}); // populate the first record in the dropdown
    });
}

HTML:

<div >
    <select  formControlName="categoryId">
        <option *ngFor="let c of categories" [value]="c.id">
            {{ c.name }}
        </option>
    </select>
</div>
  • Related