在带有角度的选择中加载默认选项 [英] Loading a default option in a select with angular

查看:31
本文介绍了在带有角度的选择中加载默认选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的选择中放置一个来自服务的默认选项.

I am trying to put a default option in my select that comes from a service.

我的选择.

<select (change)="changeValue()" [(ngModel)]="selectedValue">
<option *ngFor="let item of items" [ngValue]="item">{{ item.article }} - {{ item.value }}</option>
</select>

我传递给 ngFor 的数组.

  items: Array<any> = 
  [{ article: 'item1', value: 10 },{ article: 'item2', value: 20 }]

当我在我的应用程序中加载这个组件时,我从数据库收到一个包含这些选项之一的对象.

When I load this component in my app, I receive from the database an object that contains one of these options.

所以我想做的是,将我收到的选项设置为默认值.

So what I would like to do is, the option that I receive, set it as default.

我尝试使用 [selected] 但它不起作用.我该怎么做?

I tried with [selected] but it is not working. How can I do it?

推荐答案

基本上你缺少这些东西:

Basically you have this things missing:

  1. ngValue 应该是 item.value
  2. 您已经分配了值,因此只需更改 selectedValue 变量即可,就像我在 ngOnInit
  3. 中所做的一样
  1. ngValue should be item.value
  2. You already assingning values so just changing the selectedValue variable would work, just like I did inside ngOnInit

尝试这样的事情:

打字稿结束:

  items: Array<any> =
    [{ article: 'item1', value: 10 }, { article: 'item2', value: 20, defaultSelected: true }];
  selectedValue: string = '';
  ngOnInit() {      
    this.selectedValue = this.items.filter(a => a.defaultSelected)[0].value;
  }

HTML 结束:

<select (change)="changeValue()" [(ngModel)]="selectedValue">
<option *ngFor="let item of items" [ngValue]="item.value">{{ item.article }} - {{ item.value }}</option>
</select>

请查看此演示:https://stackblitz.com/edit/angular-v2a81r

这篇关于在带有角度的选择中加载默认选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆