【问题标题】:Get dropdown value with Angular Reactive Forms使用 Angular Reactive Forms 获取下拉值
【发布时间】:2021-09-08 18:22:00
【问题描述】:

我正在构建一个具有角度反应形式的表单。除了平台实体的下拉值之外,我可以获得所有表单值。

这是 .ts 和 .html 文件。

.html 文件

<div class="input-group mb-3">
    <label class="input-group-text" for="platformDropdown">Platform</label>
    <select class="form-select" id="platformDropdown">
        <option selected>Choose...</option>
        <option *ngFor="let platform of platforms" [ngValue]="platform.id">{{ platform.name }}</option>
    </select>
</div>

.ts 文件

userAddForm: FormGroup;
platforms: Platform[];

constructor(private formBuilder: FormBuilder, 
    private toastrService: ToastrService,
    private platformService: PlatformService) { }

ngOnInit(): void {
    this.createUserAddForm();
    this.getPlatforms();
}


createUserAddForm() {
    this.userAddForm = this.formBuilder.group({
      platformId: ["", Validators.required],
      username: ["", Validators.required],
      isFollowed: [false, Validators.required],
      isClosed: [false, Validators.required],
      lastControlDate: ["", Validators.required]
    });
}

getPlatforms() {
    this.platformService.getPlatforms()
        .subscribe(response => this.platforms = response.data);
}

add() {
    let userModel = Object.assign({}, this.userAddForm.value);
    console.log(userModel);
}

当我尝试提交表单并将数据写入控制台时,平台 id 得到的只是空白。我怎样才能达到这个值?

【问题讨论】:

    标签: angular typescript dropdown


    【解决方案1】:

    第一次看你忘了绑定控件到选择

    <select [formControl]="userAddForm.get('platformId')" class="form-select" id="platformDropdown">
    

    或者如果你已经绑定了formGroup,那么:

    <select formControlName="platformId" class="form-select" id="platformDropdown">
    

    【讨论】:

    • 啊,是的。谢谢你的建议。第二个对我来说还可以。我忘了添加 formControlName 属性。再次感谢您的帮助。
    猜你喜欢
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 2019-06-22
    • 1970-01-01
    • 2018-08-24
    • 2019-03-13
    • 2019-06-22
    相关资源
    最近更新 更多