在Angular 4中,我在json配置文件中定义了以下配置.

 countries: ['USA', 'UK', 'Canada'];
 default: 'UK'

我需要使用react 性模块在下拉列表中显示这些内容.

以下是执行此操作的代码(ts)

countries: string[] = [];
default: string;
...
this.countries = config.countries;
this.default = config.default;

html

<select id="country" formControlName="country"  >
 <option *ngFor="let c of countries" [value]="c" >{{c}}</option>
</select> 

这将完成这项工作,并在下拉列表中显示国家.

所以,我试着做这样的事情

{{c}}

然而,这是行不通的.默认情况下,如果选中,则为空值.

如何确保默认情况下 Select 了预定义值?

推荐答案

试着这样做:

component.html

<form [formGroup]="countryForm">
    <select id="country" formControlName="country">
        <option *ngFor="let c of countries" [ngValue]="c">{{ c }}</option>
    </select>
</form>

component.ts

import { FormControl, FormGroup, Validators } from '@angular/forms';

export class Component {

    countries: string[] = ['USA', 'UK', 'Canada'];
    default: string = 'UK';

    countryForm: FormGroup;

    constructor() {
        this.countryForm = new FormGroup({
            country: new FormControl(null);
        });
        this.countryForm.controls['country'].setValue(this.default, {onlySelf: true});
    }
}

Angular相关问答推荐

元件不工作时的Angular 17属性 Select 器

垫-菜单未以17.2.3角显示

在不使用散列(#)路由的情况下刷新Angular 8的SPA时,删除404错误

无法绑定到appendTo,因为它不是p-confirmPopup的已知属性

声明Angular material 中按钮的自定义 colored颜色

如何使用ChangeDetectionStrategy.OnPush?

截取提取后端S获取添加授权头的请求

如何使用formBuilder.Group()从角形表单中删除选定的选项?

如何在独立应用程序中全局禁用基于媒体查询的Angular 动画?

JsPDF Autotable 将图像添加到列中出现错误:属性getElementsByTagName不存在

Angular 13 - 使用 PUT 时出现 400 错误(错误请求)

RxJS 基于先前的数据响应执行请求(涉及循环对象数组)

Angular:try 在点击次数后禁用按钮

Rxjs Observable:仅为第一个订阅者获取 HTTP 数据,为其余订阅者获取缓存数据

react形式的formGroup.get与formGroup.controls

react表单上的自定义验证器用于密码并确认密码匹配将未定义的参数导入 Angular 4

将查询参数附加到 URL

在 Angular2 中跟踪 Google Analytics 页面浏览量

visibility:hidden

Angular 2 可用的 yeoman 生成器