Bootstrap Modal-下拉菜单的默认选择

问题描述

在Bootstrap Modal中,未显示认选项。

在下拉菜单中,我希望“请选择”是认选项,而显示为“ A”。

这是HTML代码

<div class="modal fade" id="staticBackdrop" data-backdrop="static" data-keyboard="false" tabindex="-1"
    aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="staticBackdropLabel">Add New</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <!-- <div>
                    <input
                        type="text"
                        class="form-control">
                </div> -->

                <div class="mt-3">
                    <select class="form-control"
                        formControlName="ctrlType">
                        <option value="" selected disabled>Please select</option>
                        <option
                        *ngFor="let type of formCtrlTypes">
                            {{type}}
                        </option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-danger" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success">Save</button>
            </div>
        </div>
    </div>
</div>

<div class="container">
    <div [formGroup]="form">
        <div class="form-group">
            <label class="form-control-placeholder" for="Name">Name</label>
            <input type="text" id="Name" formControlName="name" class="form-control">
        </div>


        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#staticBackdrop">
            ++ Add
        </button>
    </div>

</div>

AND Angular代码

export class ExampleComponent {
  public formCtrlTypes = [
    "A","B","C","D",]
  form = new FormGroup({
    name: new FormControl(""),formCtrls: new FormArray([])
  })
  addNewFormCtrl() {
    const add = this.form.get('formCtrls') as FormArray;
    add.push(this.fb.group({
    ctrlType: ""
    }))
    }
  constructor(private fb: FormBuilder) { }
}

输出

enter image description here

期望将“请选择”设置为认值

enter image description here

解决方法

您将表单控件错误地绑定到select元素。如果从选择元素中删除FormControlName="ctrlType",它将把禁用的选项“请选择”设置为默认选项。

使用select标签时,请考虑使用(change)事件绑定。

我在此处创建的示例示例:

https://stackblitz.com/edit/angular-oxvygr