首页 文章

Angular:如何在选择输入上设置默认选择

提问于
浏览
1

What I'm using

  • 棱角分明

  • firebase

  • 目前,标准的HTML选择组件

What I'm trying to achieve

  • 当用户在某些输入中填写一些细节时,我有一个包含许多选项的下拉列表

  • 我想选择默认选项(不是占位符,实际选择)

Question

  • 当我选择' attribute to one of the options? Let'时,例如说数组包含'album 1','album 2'和'album 3' . 默认情况下,我希望自动选择'album 2' .
<select #selectedAlbum>
<option *ngFor="let album of albumList" [value]="folder.folder_title">{{album.album.title}}</option>
</select>

2 回答

  • 2

    您可以将select元素绑定到ngModel,然后在组件初始化时将ngModel设置为所需的默认值,并通过ngModel提供的双向绑定为您选择该选项 .

    即:

    <select #selectedAlbum [(ngModel)]="mySelectedItem">
    

    在您的组件中:

    mySelectedItem: string;
    
      ngOnInit() {
        this.mySelectedItem = 'album 2';
      }
    
  • 0

    您可以添加所选属性:

    使用预定义项目的示例

    <select #selectedAlbum>
    <option *ngFor="let album of albumList" [value]="folder.folder_title" [selected]="ablum.ablum.title === 'album 2'">{{album.album.title}}</option>
    </select>
    

    使用索引的示例

    <select #selectedAlbum>
    <option *ngFor="let album of albumList; let i = index;" [value]="folder.folder_title" [selected]="i === 1">{{album.album.title}}</option>
    </select>
    

    注意:

    此方法不使用双向绑定 . 这是您目前已实施的单向绑定 . 如果你强烈建议深入挖掘表格模型 .

相关问题