albier
albier

Reputation: 21

onChange on dropdown is not working with form control

I've a problem with my dropdown. I have several values inside and like to use the selected one. This is my code, which is currently not working. The FormControll is always empty:

app.component.html

  <custom-dropdown [formControl]="majorAreaCtrl" (onChange)="onChange()" [label]="'EXPERTS.MAJOR_AREAS'|translate">
    <custom-dropdown-item *ngFor="let area of areas" [value]="area.key">
      {{ area }}
    </custom-dropdown-item>
  </custom-dropdown>

app.component.ts

export class ExpertsComponent implements OnInit {

  readonly majorAreas = MajorArea
  readonly areas = Object.values(this.majorAreas)
  readonly majorAreaCtrl = new FormControl()

  ngOnInit(): void {
    console.log(this.majorAreas, this.allExperts)
  }

  onChange() {
    console.log(this.majorAreaCtrl.value)
  }
} 

Do anyone see my mistake? Thank you in advance!!

Upvotes: 2

Views: 314

Answers (1)

William Lewis
William Lewis

Reputation: 589

You actually don't need the onChange listener (the [formControl] binding handles that). However, this requires that your custom-dropdown component implements the ControlValueAccessor interface.

If that's the case, you should be able to respond to changes by subscribing to the this.majorAreaCtrl.valueChanges Observable (for instance). Here's a small example, albeit without your custom component.

If your component doesn't implement ControlValueAccessor, I (and many others here) would be happy to help you implement it.

Upvotes: 1

Related Questions