Changing field visibility in Angular Reactive form (form validation) by toggling based on a checkbox in another component

I'm facing a challenge with a complex form where the fields depend on toggling checkboxes in a separate component (parent). My goal is to dynamically validate the form, with some fields being enabled and others disabled based on the toggling of the checkboxes. I've experimented with various examples without success...

parent.component.html

<input type="checkbox" id="check" ng-model="checked" (click)='toggleCheckform()'>
<label for="check">Check me</label>

<mat-tab label="child">
   <child [isCheck]="toggleCheck" (messageToEmit)="getMessage($event)"></child>
</mat-tab>

parent.component.ts

export class ParentComponent {

    constructor() { }

    toggleCheck: boolean = false;

    ngOnInit() {
    }

    toggleCheckform() {
        this.toggleCheck = !this.toggleCheck;
    }
}

child.component.ts

export class ChildComponent {

  @Input() isCheck: boolean;

  testForm = this.fb.group({
    Field1: ['', Validators.required],
    Field2: ['', Validators.required]
  });

  get Field1() { return this.testForm.get('Field1'); }
  get Field2() { return this.testForm.get('Field2'); }

  if(isCheck){
    this.testForm.get('Field1').disable();
  }

  onSubmit() {
    // TODO: Use EventEmitter with form value
    console.warn(this.testForm.value);
  }

  constructor(private fb: FormBuilder) {
  }

  ngOnInit() {
  }

child.component.html

    <form [formGroup]="testForm" (ngSubmit)="onSubmit()">

    <div *ngIf="isCheck">
        <div class="form-group">
           <label for="Field1">Field1</label>
                <input type="text" class="form-control" id="Field1" formControlName="Field1">
        </div>
    </div>

    <div class="form-group">
       <label for="Field2">Field2</label>
           <input type="text" class="form-control" id="Field2" formControlName="Field2">
    </div>

    </form>

My goal is to dynamically enable or disable form fields for validation based on the checkbox on the parent component. While the form works initially, it fails to update dynamically. Any assistance would be appreciated.

Answer №1

To enable/disable input, you must use a "setter" method.

_isChecked:boolean
@Input() 
set isChecked(value)
{
  this._isChecked=true;
  const control=this.testForm.get('Field1')
  if(control)
  {
    if (value)
      control.enable();
    else
      control.disable();
   }
}

get isChecked()
{
    return this._isChecked
}

IMPORTANT: When you disable a FormControl, the form.value does not include the value (you must use form.getRawValue()). Additionally, the form remains valid regardless of the disabled FormControl's value.

Check out this stackblitz example

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

What is the process for assigning a custom React component as the Type for a prop in another component?

Currently, I am working on a customized GenericModal component and would like to include an array of my ModalText components as props in the GenericModal for display purposes. I want to specifically define the type of prop being passed, rather than using s ...

The issue with Multiselect arises when the array is being set up initially

Using primeng Multiselect, I have implemented a logic to push data based on search value from the backend. To avoid the error of pushing undefined elements, initialization is required before pushing. However, when I initialize the dropdown's array var ...

Unrestricted Angular Audio Playback without CORS Restrictions

I am currently developing a web application using Angular4 that will include the feature of playing audio files. Unfortunately, I am facing an issue where I do not have control over the server serving the media files, and therefore cannot make any modifica ...

Guide on automatically inserting a colon (:) after every pair of characters in Angular

I am looking to automatically insert a colon (:) after every 2 characters in my input field: HTML <input nz-input type="text" appLimitInput="textAndNumbers" name="mac" formControlName="mac" (keydown.space)=&qu ...

A guide on creating unit tests for a login service

Seeking assistance with unit testing in Angular 7. I've written test cases but they're not included in my code coverage. Could anyone help me out? Here are my login service.ts and spec.ts files. My login.service.ts file import { Router } from & ...

Ways to display two tabs in reactjs

My typical app is running smoothly, but I am trying to implement a feature where it launches two tabs upon opening. The first tab should open with a normal path of '/' and the second one with a path of '/board'. Here's an example: ...

The p-calendar component is experiencing difficulty updating the time value when using formControlName

Currently, I am experimenting with using p-calendar to record both date and time. While I have been successful in capturing the user-selected date, I am struggling with assigning a default time using formControlName. HTML: <p-calendar id="calenderid" ...

The ngmodel variable is not responding to dynamic changes

I'm currently working on dynamically changing a date and getting it to reflect in the view, but for some reason it's not showing up. When the date is hard-coded in an array like this, it works perfectly fine and shows up in the view. My date : Ar ...

Creating a conditional property in TypeScript based on an existing type - a comprehensive guide

Imagine if I had the following: type Link = { text: string; link: string; } interface BigLink extends Link { some: number; something: string; else: string; } However, there's a variable that shares all these properties except for the fact ...

The tooltip is being truncated

https://i.sstatic.net/o41Qz.png Struggling with a tooltip that keeps getting cut off? I've tried everything and still can't get it right. <th class="fd-table--header-cell" scope="col"> <p class=&q ...

Issues with Rxjs pipe and Angular's Http.get() functionality are causing complications

Working with an Angular 4 Component that interacts with a Service to fetch data is a common scenario. Once the data is retrieved, it often needs to be transformed and filtered before being utilized. The prevailing method for this task is through the use of ...

When a class decorator is returned as a higher-order function, it is unable to access static values

Check out this showcase: function Decorator(SampleClass: Sample) { console.log('Inside the decorator function'); return function (args) { console.log('Inside the high order function of the decorator: ', args); let sample = ...

How does one distinguish between the uses of "any" and "any[ ]"?

Exploring the Difference Between any and any[ ] An Illustrative Example (Functioning as Expected) variable1: any; variable2: any[]; this.variable1 = this.variable2; Another Example (Also Functioning as Intended) variable1: any; v ...

Activate TypeScript EMCAScript 6 support for Cordova projects in Visual Studio

I am interested in utilizing the async/await feature of TypeScript in my VS2015 Cordova project. I have updated "target": "es6" in tsconfig.json Although there are no errors shown in intellisense, I encounter the following error while building the project ...

Issue: Module 'stylelint' not found in Angular Project

I've been attempting to execute this command to validate all of the .scss files (and even tried with .css files) and I keep encountering this error. $ stylelint "apps/**/*.scss" It worked once before but not anymore, even after restarting my compute ...

Is there a way to ensure that fields in a sub component are validated whenever we attempt to switch the Tab using a route

Hi there, I could really use your assistance. I've done some research, but I haven't been able to find a suitable solution for my problem. I have this shared component that contains the following code which enables tab navigation through various ...

Implementing Angular routing in an ASP.NET Core 2 project

I recently encountered an issue with serving my Angular project within an ASP.NET Core project. After building the Angular app with "ng build --prod" and placing it in the wwwroot directory, I set up the ASP project to serve the site. Since I do not have a ...

Learn the technique of passing dual onClick parameters to a single function in React

I am working on a function named Test where I need to pass two onClick references. const Test = ({ onConnect }:{ onConnect:any }, { onDisconnect }:{ onDisconnect:any }) => { return ( <div> <DrawDiagram /> <button onClick ...

The search for 'partition' in 'rxjs' did not yield any results

Recently, I attempted to incorporate ng-http-loader into my Angular project. After successfully installing the ng-http-loader package, I encountered an error during compilation. The specific error message displayed was: export 'partition' was ...

Avoiding the occurrence of routing errors when an error arises in Angular 2

I've observed that whenever an error occurs in my Angular 2 application, it also disrupts the routing. Is there a method to address this and avoid the issue of breaking routing? ...