Subscribing to valueChanges in reactive forms to dynamically update checkbox options

My goal is to create a select dropdown with options for bmw, audi, and opel. The user can only select one option from the dropdown, but they should also have the ability to select the options that were not chosen using checkboxes.

cars = [
    { id: 1, name: 'bmw' },
    { id: 2, name: 'audi' },
    { id: 3, name: 'opel' }
];

Here's how it should work:

For instance, if the user selects bmw in the dropdown, then two checkboxes for audi and opel should be displayed since those are the remaining options. If the user changes their selection from bmw to something else, the checkboxes should update accordingly to display the available options.

Form setup:

this.firstStepForm = this.fb.group({
  cars: [''], // select
  models: this.fb.array([]) // checkboxes
});

Setting up checkboxes:

private setupControls(details: any): void {
let control = <FormArray>this.firstStepForm.controls.models;

details.forEach(x => {
  control.push(this.fb.group({
    id: x.id,
    name: x.name
  }))
})

Subscribing to changes:

this.firstStepForm.get('cars').valueChanges.subscribe((carId: number)

Check out a simple example on stackblitz

I am currently trying to figure out how to determine the index of the selected car and update/remove the checkboxes accordingly.

Desired Results:

  1. Checkboxes should display only the options that were not selected in the dropdown
  2. If the selected value changes, checkboxes should update to show the remaining options.

Queries:

Is there a simpler way to achieve this without using removeAt (FormArray)? Maybe I could use underscoreJs _filter function to filter out values based on the id, but how do I filter out FormArray items based on a specific value (:id)?

let magic = _.filter(arr, function (num) { return num != carId });

console.log('magic: ', magic);

Answer №1

give it a shot:

export class AppComponent implements OnInit {
  vehicles = [
    { id: 1, name: 'toyota' },
    { id: 2, name: 'honda' },
    { id: 3, name: 'ford' }
  ];
  firstStepForm: FormGroup;
  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.buildFirstStepForm();
    this.firstStepForm.get('vehicles').setValue(this.vehicles[0].id);
    this.onChange(this.vehicles[0].id); // initial first item select
  }

  onChange(e){
    let arr = this.vehicles.filter(item => item.id != e);
    this.models.controls = [];
    this.setupControls(arr)
  }

  get models(): FormArray {
    return <FormArray>this.firstStepForm.controls.models;
  }

  private buildFirstStepForm(): void {
    this.firstStepForm = this.fb.group({
      vehicles: [''],
      models: this.fb.array([])
    });
  }

  private setupControls(details: any): void {
    details.forEach(x => {
      this.models.push(this.fb.group({
        id: [x.id],
        name: [x.name]
      }))
    })
  }
}

html:

<form [formGroup]="firstStepForm" (ngSubmit)="submit()">
    <p>Choose:</p>
    <select formControlName="vehicles" (change)="onChange($event.target.value)">
        <option *ngFor="let vehicle of vehicles; let i = index" [value]="vehicle.id">
            {{vehicle.name}}
        </option>
    </select>
  <br>
  <br>
  <br>
  <p>Options:</p>
  <div class="form-check" *ngFor="let type of models.controls; let i = index">
    <label formArrayName="models">
      <input type="checkbox">{{type.value.name}}
    </label>
  </div>
</form>

DEMO

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Verify if the keys are present within the object and also confirm if they contain a value

How can we verify keys and compare them to the data object? If one or more keys from the keys array do not exist in the object data, or if a key exists but its value is empty, null, or undefined, then return false; otherwise, return true. For example, if ...

Having issues with Angular 2/4 unable to read an object within the initForm() function

In the process of creating an edit form using Angular, I am facing a problem with understanding the lifecycle of the object retrieved from my backend server. After making a call to my service in ngOnInit(), I receive valid data. However, when I assign this ...

Reactjs may have an undefined value for Object

I have already searched for the solution to this question on stackoverflow, but I am still confused. I tried using the same answer they provided but I am still getting an error. Can someone please help me resolve this issue? Thank you. const typeValue = [ ...

retrieve object from s3 using angular and open it as a pdf

I'm attempting to access a file from an s3 bucket using Angular and display it as a PDF. I have a node service set up to retrieve the object, which I then call from Angular. However, when I try to open the PDF in Angular, it appears as a blank (white) ...

Incorporate Sendbird into Angular 6 for seamless communication integration

I recently started delving into the world of angular6 and nodejs. I am eager to integrate sendbird with Angular6, but I'm struggling to find a clear starting point. If anyone has successfully done this before, I would greatly appreciate some guidance ...

What is the process for retrieving the serial number of a hardware device in Ionic 2?

I recently encountered an issue while trying to retrieve device details. I was able to fetch the UUID of the hardware device, but unfortunately, the serial number was inaccessible. Any suggestions or insights on how to obtain the serial number would be g ...

An email value being recognized as NULL

create-employee.html <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <span><input type="text" [required]="!standingQueue" class="form-control" name="exampleInputEmail1" ...

What is the reason for TypeScript not displaying a type mismatch error in this particular instance?

After starting to use React with TypeScript, I defined my types as follows: type CardInfo = { cardIndex: null | number; title: string; note: string; _id: string; from: string; cardId: string; }; type ContentType = { title: string; note: st ...

Getting a blank request body error while receiving data from an Angular 4 application in Express

My express route is indicating that the body of the request being sent is empty, according to req.body. The main node file looks like this - var express = require('express'); var bluebird = require('bluebird') const bodyParser = requ ...

Error message: "Lazy-loaded modules encounter a TypeError stating that '' is not a function when accessed through NGINX."

Hey, I've got some distribution files for you to check out: AOT-enabled dist with Lazy Modules No AOT Lazy Modules dist AOT without Lazy Modules dist Here's what's been going on: When served locally with webpack-dev-server or live-serve ...

Similar to `util.inspect` in Node.js, Deno also has a function

Is there a utility function in Deno that can stringify an Object or primitive similar to Node.js util.inspect? For instance, if I have a JSON object in Node.js and want to display its contents: > m = {k1:'v1', k2:'v2'} { k1: ' ...

No errors encountered during compilation for undefined interface object types

Hey there, I'm currently exploring the Vue composition API along with Typescript. I'm facing an issue where I am not receiving any errors when an interface does not align with the specified types for that interface. Although my IDE provides aut ...

Having trouble getting ng-click to function properly in TypeScript

I've been struggling to execute a function within a click function on my HTML page. I have added all the TypeScript definition files from NuGet, but something seems to be going wrong as my Click Function is not functioning properly. Strangely, there a ...

Utilizing an object property for @Input binding in Angular: A step-by-step guide

I am currently delving into Angular and Ionic Frameworks, honing my skills through practice. I'm encountering an issue with a basic @Input test, where I am trying to iterate through an array of Tab Pages and then display each tab using <ion-tab> ...

Creating Empathetic User Experiences with Next 12 and SWC: A Guide to Harnessing import.meta.url

In my Next.js 12 App with the Rust Compiler, I am utilizing Jest and WebWorkers. In one of my files, I am using import.meta.url. to create the worker. The issue arises when Jest throws an error, stating that import.meta.url cannot be used outside of an ES ...

Can Angular Universal SSR be activated specifically for Googlebot User Agents?

I am aiming to activate Angular Universal SSR only when the User Agent is identified as Googlebot. However, I am uncertain about how to instruct Angular Universal SSR to deliver server side rendered HTML exclusively if the User Agent is Googlebot. server ...

Is it more efficient to wait for the server to respond, or should I update the client immediately

Today, I found myself contemplating an interesting question. As I work on developing a Single Page Application (SPA) using Angular, I am focusing on creating a calendar module similar to Google Calendar. This module will allow users to add, edit, and remov ...

What is the process for changing the border color of a material selection?

Is it possible to customize the border color of a material select element? I attempted changing the border color using css from: to this: Any suggestions on how to achieve this? Appreciate any assistance you can provide! ...

How to align an image in the center of a circular flex container

I'm facing an issue in my Angular project where I have the following code snippet: onChange(event: any) { var reader = new FileReader(); reader.onload = (event: any) => { this.url = event.target.result; }; reader.readAsData ...

Using TypeScript and the `this` keyword in SharePoint Framework with Vue

I'm currently developing a SharePoint Framework web part with Vue.js. Check out this code snippet: export default class MyWorkspaceTestWebPart extends BaseClientSideWebPart<IMyWorkspaceTestWebPartProps> { public uol_app; public render(): ...