Angular2 select default first option

前端 未结 10 1552
半阙折子戏
半阙折子戏 2021-01-04 08:32

How do i select the first option in a select by default in angular 2 the following code don\'t seems to work.


                        
    
提交评论

  • 2021-01-04 09:28

    1) I hope this approach can help as well!

    <select id="category" name="category" class="form-control" formControlName="category">
         <option [attr.selected]="true" [ngValue]="categories[0].id" >{{categories[0].name}}</option>
         <option *ngFor="let cat of categories.slice(1)" [ngValue]="cat.id">{{cat.name}}</option>
     </select>
    

    2 ) If you are using a Form control you need just to set it like default value

     this.fgAddingProduct = new FormGroup({
            category: new FormControl(this.categories[0].id, [Validators.required]),
     });
    

    And use a normal *ngFor

    <select id="category" name="category" class="form-control" formControlName="category">
                <option *ngFor="let cat of categories" [ngValue]="cat.id">{{cat.name}}</option>
            </select>
    
    0 讨论(0)
  • 2021-01-04 09:30

    If you use Model Driven Forms you can set the selected default value of your <select> in your component (ngOnInit())

    componenet.file.ts

    public fieldSelect : any;
    
    ngOnInit(){
        ...
        this.fieldSelect= { key: "mySelect", label: "Example Select"};
        this.controlsConfig= [];
        this.controlsConfig[this.fieldSelect.key] =  [""];
        this.myFormGroup= this.formBuilder.group(this.controlsConfig);
    ...
    }
    

    component.file.html

    <div class="col-md-2" [formGroup]="myFormGroup">
        <select (change)="onChangeTypeImp($event)" [formControlName]="fieldSelect.key">
           <option *ngFor="let item of items;" [value]="item">{{item}}</option>
       </select>                      
    </div>
    

    Model-Driven Forms: While using directives in our templates gives us the power of rapid prototyping without too much boilerplate, we are restricted in what we can do. Reactive forms on the other hand, lets us define our form through code and gives us much more flexibility and control over data validation.+

    There is a little bit of magic in its simplicity at first, but after you're comfortable with the basics, learning its building blocks will allow you to handle more complex use cases.

    [example]

    0 讨论(0)
  • 2021-01-04 09:32

    Or simply like this :)

    <option *ngFor="let value of values; let i = index"
        [ngValue]="value"
        [attr.selected]="!i"
    >{{item}}</option>
    

    Enjoy !

    0 讨论(0)
  • 提交回复
    热议问题