【问题标题】:Initialize dropdown in Angular Formgroup在 Angular Formgroup 中初始化下拉菜单
【发布时间】:2017-09-14 16:47:07
【问题描述】:

我正在尝试为使用 Angular FormGroup 的表单中的下拉控件设置默认值(我使用的是 Angular 4)。下拉列表很好地填充了给定的列表,但未设置默认值。此外,它在代码中没有显示任何错误以下是我正在使用的代码--

HTML 代码

    <div class="col-xs-2">
    <label class="control-label" for="Country">Country</label>
    <select formControlName="CountryID" [(ngModel)]="CountryID" class="form-control">
        <option *ngFor="let country of Countries"  [ngValue]="country.CountryID">{{country.CountryName}}</option>
    </select>
</div>

打字稿代码

ngOnInit() {
        this.Countries = [
            { "CountryID": 0, "CountryName": "Select Country" },
            { "CountryID": 1, "CountryName": "Country 1" },
            { "CountryID": 2, "CountryName": "Country 2" },
            { "CountryID": 3, "CountryName": "Country 3" },
            { "CountryID": 4, "CountryName": "Country 4" },
            { "CountryID": 5, "CountryName": "Country 5" }
        ];

        this.inputProcessingForm = this._domBuilder.group({
            CandidateBuilderAppId: [''],
            FirstName: ['Amit'],
            MiddleInitial: '',
            LastName: '',
            Gender: 'S',
            DateOfBirth: new Date(),
            SocialSecurityNumber: 0,
            PersonalEmail: 'amanand@liventus.in',
            CorpEmail: '',
            HomePhone: '',
            WorkPhone: '',
            WorkCellPhone: '',
            WorkFax: '',
            WorkExtension: '',
            RemoteFax: '',
            Address1: '',
            Address2: '',
            CountryID: 0,
            State: 0,
            City: 0,
            ZipCode: 0
        });
}

如果我做错了什么,请提出建议。任何帮助将不胜感激。

【问题讨论】:

    标签: angular angular2-forms


    【解决方案1】:

    您可以尝试从模板中删除[(ngModel)]="CountryID" 吗?因为根据docs,我猜测必须使用其中一种约定(formControlName 如果使用反应式表单,ngModel 如果使用模板驱动表单),否则可能会混淆“访问器”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-16
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 2021-03-26
      • 1970-01-01
      相关资源
      最近更新 更多