简体   繁体   中英

Angular 4 bind select option to controller

I get a list of categories from my service, and i want to bind the category of my controller with the option selected in my select, what i tried:

<select class="form-control" id="category" [(ngModel)]="category">
        <option *ngFor="let category of categoryservice.getCategories()">
          {{category.name}}
        </option>
</select>

My controller:

category : Category = new Category(0, '', '', 0);

constructor(private categoryservice : CategoryService) { }

ngOnInit() {
}

With this code i get the error: If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions.

But i'm not using ngModel within a form, so i don't know what could be the problem.

Thanks!

Just add a name attribute to your select

    <select class="form-control" name="categoryDrpDown" id="category" 
 [(ngModel)]="category">
        <option *ngFor="let category of categoryservice.getCategories()" [ngValue]="category">>
          {{category.name}}
        </option> 
     </select>

Also you need to call the method getCategories() inside ngOninit and use the categories array only in template.

<select class="form-control" id="category" [(ngModel)]="category">
        <option *ngFor="let category of categories">
          {{category?.name}}
        </option>
</select>

and inside component

category : Category = new Category(0, '', '', 0);
categories : Category[] = []
constructor(private categoryservice : CategoryService) { }

ngOnInit() {
   this.categoryservice.getCategories().subscribe((response) => {
        this.categories = response;
   });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM