【问题标题】:Can I use [formControl] without also needing [formGroup]?我可以在不需要 [formGroup] 的情况下使用 [formControl] 吗?
【发布时间】:2019-02-19 03:30:30
【问题描述】:

我在我的 UI 中使用下拉菜单,但是当我开始使用 [formControl] 时,我收到了错误:

找不到具有未指定名称属性的控件

我在 app.module.ts 中使用 ReactiveFormsModule。

我在 Google 上搜索并发现解决方案是在父 div 中使用 [formGroup],但我不确定如何正确实施,因为我正在从 subscribe 中定义我的 formControl .

myComp.component.html

<div class="exceptional-status">
  <select #exceptionalSelect id="excep-status-dropdown" [formControl]="select">
    <option disabled value="default">--Exceptional statuses--</option>
    <!-- other options here with *ngFor -->
  </select>
</div>

myComp.component.ts

select: FormControl;

mySubscription() {
  this.myService.myFunct.subscribe(res => {
    this.select = new FormControl(res.status)
  });
}

【问题讨论】:

标签: javascript html angular typescript


【解决方案1】:

是的,您可以在没有 FormGroup 的情况下使用 FormControlDirective

Angular 期望 FormControl 被定义:

select = new FormControl();

mySubscription() {
  this.myService.myFunct.subscribe(res => {
    this.select.setValue(res.status)
  });
}

【讨论】:

  • 啊太棒了!我认为它可能是类似的东西,但不知道如何去做。我刚刚在 Google 上发现了 setValue()patchValue() 之间的区别,现在我选择了 patch
【解决方案2】:

是的,你可以在没有 FormGroup 的情况下使用它。

select = new FormControl();

对于设置值:-

select.setValue('your data here');

获取值:-

select.value

【讨论】:

    【解决方案3】:

    为什么要在订阅中定义表单控件?我的建议是在订阅之外构建表单骨架并使用

    填充控件
    mySubscription() {
      this.myService.myFunct.subscribe(res => {
        this.controls['select'].patchValue(res.status);
      });
    }
    

    【讨论】:

    • controls 是从哪里来的?
    猜你喜欢
    • 2017-01-28
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多