physicsboy
physicsboy

Reputation: 6326

Can I use [formControl] without also needing [formGroup]?

I am using a dropdown in my UI, but when I come to use [formControl] I am getting the error thrown:

Cannot find control with unspecified name attribute

I am using ReactiveFormsModule in my app.module.ts.

I have Google'd and found that a solution is to use [formGroup] in the parent div, but I'm unsure of how to implement properly as I am defining my formControl from within a subscribe.

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)
  });
}

Upvotes: 24

Views: 38912

Answers (3)

Ganesh K
Ganesh K

Reputation: 101

Yes, you can use it without FormGroup.

select = new FormControl();

For set the value:-

select.setValue('your data here');

To get the value:-

select.value

Upvotes: 2

yurzui
yurzui

Reputation: 214067

Yes, you can use FormControlDirective without FormGroup.

Angular expects FormControl to be defined:

select = new FormControl();

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

Upvotes: 19

filipbarak
filipbarak

Reputation: 1905

Why would you define the form control within the subscribe? My advice would be to structure the form skeleton outside the subscription and just populate the control using

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

Upvotes: 0

Related Questions