select option not working with ng-model in angular

2020-02-14 07:44发布

问题:

I have a select box where I show elements from a list Code Snippet:

export class CreateauctionComponent implements OnInit{

    createAuctionForm: FormGroup;
    test:any = ["cat","dog"];

    constructor(private _formBuilder: FormBuilder,private _categories: UserCategoriesForAuctionService){
        //
    }
}

In HTML rendered as:

<div class="form-col">
    <h5><span style="color:red;">*</span>{{'createAuction.category' | translate}}:</h5>
    <select class="form_cbx long-select" name="" ng-model="test">
        <option  ng-options="t in test">{{t}}</option>
    </select>   
</div>

I am not able to see any values. Only one blank field in the list. Can anyone direct what is the issue here?

回答1:

It should be,

<select [(ngModel)]="selectedanimal" (ngModelChange)="onChange($event)">
  <option *ngFor="let c of test" [ngValue]="c"> {{c}} </option>
</select>

DEMO



回答2:

You need to use compareWith property on select tag, but If you are using angular 4, your html still looks like using angularJs.

HTML File :

<select [compareWith]="byAnimal" [(ngModel)]="selectedAnimal">  
  <option *ngFor="let animal of animals" [ngValue]="animal">
    {{animal.type}}
  </option>
</select>

TS File

byAnimal(item1,item2){
  return item1.type == item2.type;
}

One of the best soltion from this link



回答3:

Correct Way would be:

<select id="select-type-basic" [(ngModel)]="status">
    <option *ngFor="let status_item of status_values">
    {{status_item}}
    </option>
</select>

Value Should be avoided inside option since that will set the default value of the 'Select field'. Default Selection should be binded with [(ngModel)] and Options should be declared likewise.

status : any = "Completed";
status_values: any = ["In Progress", "Completed", "Closed"];


标签: angular