How to dynamically bind formControl in Angular based on an expression

I am dealing with 2 arrays in the request data - one for included products and the other for excluded products. It is important to note that these two arrays cannot be used simultaneously. Therefore, my HTML code looks like this:

<input [formControl]="this.exclude$ ? excludedFormControl : includedFormControl>
<mat-slide-toggle (change)="excludeChange($event.checked)"></mat-slide-toggle>

Below is my TypeScript code:

exclude$ = new BehaviorSubject<boolean>(false);

currentFilter = {
    productsSection: {
        includedIds: [],
        excludedIds: [],
    },
};

includedFormControl: FormControl = new FormControl(
    this.currentFilter.productsSection.includedIds ? this.currentFilter.productsSection.includedIds : [],
);

excludedFormControl : FormControl = new FormControl(
    this.currentFilter.productsSection.excludedIds? this.currentFilter.productsSection.excludedIds: [],
);

excludeChange(value: boolean): void {
    this.filterForm.patchValue({
        includedIds: [],
        excludedIds: [],
     });
     this.exclude$.next(value);
}

showFormValue() {
    console.log(this.filterForm.value);
}

Issue: The problem arises when I switch the toggle as the excludeChange function is triggered but the input still writes data into the includedIds field instead of the intended exclusion.

Answer №1

To gain access, you must register via the exclude$.

<input [formControl]="excluded ? excludedFormControl : includedFormControl">

In the component.ts document, make sure to declare excluded.

excluded = false;
this.exclude$.subscribe(res => {
  this.excluded = res;
});

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

Leverage the keyof operator for automatic determination of return type

My interface looks like this: interface ResourceState<ItemType> { rows: ItemType[], store: Record<String, ItemType> } To create a root state, I use the following structure: RootState{ car: ResourceState<Car> user: ResourceState<User&g ...

Guide on integrating two separate UI (CSS) frameworks, one optimized for mobile and the other for desktop, within a single Angular project

I am tasked with developing both mobile and desktop versions of a web application using two different CSS frameworks, Ionic 4 and Bootstrap, for different use cases. Despite these differences, the rest of the app remains the same, utilizing Ngrx store and ...

Invoke PrimeNG calendar through code

Currently, I am facing an issue while using the PrimeNG components with Angular 4. My concern is regarding how to display the calendar when a button is clicked. You can view the Plunker example here @Component({ selector: 'my-app', template: ...

Angular 10 edit mode issue: Unable to set selected value in dropdown

Why is the value from the database not selected in the edit mode of the form? Even though I am getting the correct value in 'service.formData.SalesRepId', it is not being selected. Is there something I am overlooking? https://i.sstatic.net/DLtfr ...

When attempting to upload a selfie image in Ionic 4, an error occurs: Uncaught Promise Error: TypeError - Unable to read property 'subscribe' of undefined

Currently utilizing Ionic version 4 and trying to capture an image from the phone camera for upload. I've been working on this for the past two days in an attempt to find a solution. Appreciate any assistance. const options: CameraOptions = { qual ...

What is the best method for connecting a ref to a component that I am duplicating with React.cloneElement?

Hi everyone! I'm trying to pass a ref into my component so that I can access the variables on the component like state. The only problem is, I'm having trouble getting it to work. It needs to be functional for both classes and functions. Every t ...

CoursesComponent does not contain a Directive annotation

I have been following a tutorial online at this link: https://www.youtube.com/watch?v=_-CD_5YhJTA Unfortunately, I keep encountering the following error message: EXCEPTION: No Directive annotation found on CoursesComponent Here is an excerpt from my a ...

Having difficulty generating a new object and implementing the export class feature in Angular 2

Here is the UserDetails class defined: export class UserDetails { name:string; phoneNumber:string; email:string; password: string; } Below is a service where userDetails are utilized:: import { Injectable } from '@angular/core'; import { Ht ...

Facing issues using Angular 5 for PUT requests due to 401 errors

When attempting to update data using the PUT Method in my angular service and express routes, I encountered a 401 error. Here is my service code: //401 makeAdmin(_id) { this.loadToken() let headers = new Headers() headers.append('Authorization& ...

How does a brand new installation of VSCode believe it comes pre-equipped with TypeScript capabilities?

Operating on Windows 10 Enterprise, After investing several hours and experimenting on various VMs, Interesting Observation #1 Upon opening a .ts file in vscode, it appears to be recognized as TypeScript 2.3.4 as per the screenshot provided below: http ...

Steering clear of Endless Loops in Spring Boot

When utilizing a Spring Boot Rest API, I successfully prevented an infinite loop by using @JsonIgnore. However, in the postman response, the related list on the many side appears as null. How can I go about displaying this related list in Angular even if i ...

Bidirectionally update values between a parent and child component in Angular version 5.2.0

I have developed a reusable component for autocomplete functionality. When a value is selected, it is sent to the parent component. // Child Component empleado: Empleado; @Output() empleadoEvent = new EventEmitter<Empleado>(); .... onSelect() { ...

The flexibility of adjusting the percentage in the ng-circle-progress feature

Currently, I am utilizing ng-cycle-progress in my Angular progress. Here is the HTML code: <circle-progress [percent]="score" [radius]="100" [outerStrokeWidth]="16" [innerStrokeWidth]="8" [outerStrokeColor]="'#78C000'" [innerStrok ...

In a functional component in Typescript, what data type should be used for a parameter that accepts an array of objects?

const FormData = ({ dataArray }: object[]): JSX.Element => { console.log("Array of Objects",dataArray) //This is a large form component.... }); The dataArray contains multiple objects, how can I specify a specific type for these components ...

Eslint encountered an issue while parsing: Unable to access tsconfig.json

My directory structure looks like this: -projects --MyProject ---MyDir tsconfig.json eslinttrc.json Inside my eslinttrc.json file, I have the following configuration: "parserOptions": { "ecmaVersion": " ...

Specify specific data types for a dynamically generated class method

Imagine having a scenario with the following class: class Example { method1 = this.generateDynamicFunction((param: string) => { return "string" + param; }); method2 = this.generateDynamicFunction((param: number) => { return 1 + param; ...

calculating the dynamic height of a document from top to bottom using Angular

Is there a way to dynamically calculate the height of each page from top to bottom in Angular? The syntax that works in JavaScript seems to give an error in Angular. console.log( (document.height !== undefined) ? document.height : document.body.offsetHeigh ...

Creating a TypeScript type or interface that represents an object with one of many keys or simply a string

I am tasked with creating an interface that can either be a string or an object with one of three specific keys. The function I have takes care of different errors and returns the appropriate message: export const determineError = (error: ServerAlerts): ...

How Typescript Omit/Pick erases Symbols in a unique way

Recently, I have delved into TypeScript and started working on developing some custom utilities for my personal projects. However, I encountered an issue with type mapping involving Pick/Omit/Exclude and other typing operations where fields with symbol key ...

extracting data from checkbox to use in an angular function upon being selected

Currently, I am creating a list of checkboxes with distinct string values: heading, paragraph, list, table, visualtitle. I believe the current approach using (change)="onChange('heading', $event.target.checked) may not be the best way to han ...