Tips for resolving the issue where a radio group in Angular does not impact other items

Here's the code

list.component.html

<form nz-form [formGroup]="taskFormGroup" (submit)="saveFormData()">
        <div nz-row *ngFor="let remark of checklis>
          <div nz-col nzXXl="12" *ngFor="let task of remark.tasks" style="padding: .5rem;">
<nz-form-item>
                  <nz-form-control>
                    <nz-radio-group formControlName="status" name="status" (ngModelChange)="onChangeStatus($event)">
                      <label nz-radio nzValue="true">Passed</label>
                      <label nz-radio nzValue="false">Failed</label>
                    </nz-radio-group>
                  </nz-form-control>
                </nz-form-item>

    <nz-form-item>
      <nz-form-control>
        <textarea nz-input placeholder="{{ remarkPlaceHolder }}" class="remarks-textarea" type="text"
          name="otherRemark"></textarea>
      </nz-form-control>
    </nz-form-item>
</div>
</div>
</form>

list.component.ts

checklist = [
    {
      "id": "txv3vvBr8KYB",
      "assetType": {
        "id": "1fKBO4w0XHg7H",
        "code": "PRD",
        "name": "Printing1"
      },
      "tasks": [
        {
          "id": "1fKBO4w0XHg7H",
          "name": "Task 1",
          "description": "Check oil spill"
        },
        {
          "id": "ESOSA6aCrOER",
          "name": "Sample1",
          "description": "Desc1"
        }
      ]
    },
    {
      "id": "EwQciw9whx6B",
      "tasks": [
        {
          "id": "1nU7uASqfvLPD",
          "name": "TASK8888",
          "description": "DESC8888"
        },
        {
          "id": "EwQciw9whx6B",
          "name": "TASK9999",
          "description": "DESC9999"
        }
      ]
    }
  ];

constructor (private fb: FormBuilder) {}


  onChangeStatus(event: any) {
    switch (event) {
      case true:
        this.otherRemark = '';
        this.remarkPlaceHolder = 'Remarks (optional)';
        break;
      case false:
        this.remarkPlaceHolder = 'Remarks (required)';
        break;
      default: break;
    }
  }

Trying to display optional or required remarks in textarea based on pass/fail. When selecting pass, it affects all items. How to fix this issue?

Example:

1. Sample 1

2. Sample 2

Choosing pass for Sample 1 displays optional remarks for both samples. How to resolve?

Thank you.

Answer №1

In order to have different placeholder text in textboxes based on the selected radio option, you will need to keep track of a flag that monitors the changes in the corresponding radio option.

1. Populate the flag array based on the data in the checklist.

  textBoxStatus: string[][] = [];

  constructor(private fb: FormBuilder) {
    this.taskFormGroup = this.fb.group({
      remark: "",
      status: ["", [Validators.required]]
    });

    for (let parent of this.checklist) {
      this.textBoxStatus.push([]);
      for (let child of parent.tasks) {
        this.textBoxStatus[this.textBoxStatus.length - 1].push('false');
      }
    }
  }

2. Set up the HTML template to utilize this flag array

<form nz-form [formGroup]="taskFormGroup" (submit)="saveFormData()">
    <div nz-row *ngFor="let remark of checklist; let parent=index">
        <hr>
    Parent {{parent}}
        <hr>
        <div nz-col nzXXl="12" *ngFor="let task of remark.tasks; let child=index" style="padding: .5rem;">
            <hr>
      Child {{parent}}.{{child}}
      <hr>
            <nz-form-item>
                <nz-form-control>
                    <nz-radio-group formControlName="status" name="status" (ngModelChange)="onChangeStatus($event, parent, child)">
                        <label nz-radio nzValue="true">Passed</label>
                        <label nz-radio nzValue="false">Failed</label>
                    </nz-radio-group>
                </nz-form-control>
            </nz-form-item>

            <nz-form-item>
                <nz-form-control>
                    <textarea nz-input placeholder="{{ textBoxStatus[parent][child] == 'true' ? 'Remarks (optional)' : 'Remarks (required)' }}" class="remarks-textarea" type="text"
          name="otherRemark"></textarea>
                </nz-form-control>
            </nz-form-item>

        </div>
    </div>
</form>

3. Update flags based on user action

onChangeStatus(event: string, parent: number, child: number) {
  this.textBoxStatus[parent][child] = event;
}

View 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

What is the best way to choose the member variables in this specific data structure?

I have been assigned the task of retrieving the cities from various countries, but I am unsure of the best approach to do so. How can I easily extract city names like: For example, for USA it would be NYC and SFO. I attempted using the code snippet cityD ...

How to utilize *ngFor alongside the async pipe for conditional rendering in Angular 8 HTML

.html <ng-container *ngFor="let contact of listContact | async; let index = index;"> <h6 class="title" *ngIf="contact && contact['type']"> {{contact['type']}} </h6> <div> {{conta ...

Angular error TS2322 arises when attempting to assign a type of 'Observable<{}>' with the share() operator

Currently diving into Angular 5, I've been exploring the Observable/Observer pattern to facilitate event sharing and data changes among subscribers. Below is a snippet of the code in question: ... @Injectable() export class NidoService { ... eve ...

Adding a dynamic click event in HTML using IONIC 4

I've created a function using Regex to detect URL links and replace them with a span tag. The replacement process is working fine, but I'm facing an issue where when I include (click)="myFunction()" in the span, it doesn't recognize the cli ...

Explain the functionality of the Angular EventListener that is triggered on the scroll event of

Currently, I am exploring ways to track the position of the navbar beneath the landing page. The goal is for the navbar to become sticky at the top once it reaches that position until you scroll back up. Despite trying various solutions on Stack Overflow a ...

Can I modify the cookie domain for NestJS SessionModule on a per-request basis?

I am currently using NestJS with SessionModule to handle user cookies successfully. However, I have a requirement to override the domain name for certain requests. I am uncertain about how to achieve this within NestJS, as the domain setting appears to b ...

What is the reason for array.push not functioning properly on a collection that contains table data in Angular4 and PrimeNG?

After including the following HTML code: <p-dataTable selectionMode="single" [(selection)]="selectedUsers" dataKey="id" ...

What are the steps to implement Bootstrap validation in conjunction with HTMX hx-post requests?

I am currently working on a project that utilizes the Bootstrap frontend toolkit. Bootstrap has built-in support for HTML5 form validation with custom styles. In order to enable this feature, the form must have the novalidate attribute: <form class=&quo ...

Tips for testing a void method using unit testing

I'm aiming to increase my code coverage by writing unit tests. I have a method that simply triggers a notification without needing a response. How can I write a unit test for it? public error(message?: any, ...optionalParams: any[]) { if (this.is ...

Enforce numerical input in input field by implementing a custom validator in Angular 2

After extensive research, I was unable to find a satisfactory solution to my query. Despite browsing through various Stack Overflow questions, none of them had an accepted answer. The desired functionality for the custom validator is to restrict input to ...

Steps for creating an Observable<Object[]> using data from 2 different API requests

My goal is to retrieve an Observable<MyResult[]> by making 2 separate API calls to load the necessary data. The first call is to load MyItem. The second call is to load Gizmos[] for each item. In a previous question, I loaded the second API into t ...

Error occurs on Chrome while Angular 7 HTTP POST works fine on Edge and Firefox

My application is experiencing a strange issue where the HTTP POST method works fine on Firefox and Edge browsers, but not on Chrome. The application is built using Angular 7 and .NET Core 2.2. It has a CRUD example that functions correctly in all browser ...

Whenever I make a POST request to the API in Ionic 2, I encounter a "Connection refused (x192)" error

I have been struggling with an error in my code for the past two days and I can't seem to find a solution. Can someone please help me with this? The error message is as follows: [Error] WebSocket network error: The operation couldn’t be complet ...

What is the process for deconstructing errors from the RTK Query Mutation Hook?

Currently, I am utilizing redux toolkit query for handling my data fetching API. One issue that I have encountered is with error handling. When an error is returned from the server, it comes in as an object with nested data. However, when trying to access ...

Creating Reactive Form Validators in Angular 5: Implementing a Custom Validator to Compare Two Form Controls

To ensure my save button is disabled only when validation fails, I have implemented the following logic: private createForm() { this.commentForm = new FormGroup({ 'startTime': new FormControl(this.startTime, [ this. ...

Ensure that the function's parameters are entered exclusively through TypeScript interfaces

How can I efficiently organize and maintain the function's arguments below without utilizing Typescript? Can this be achieved using Interfaces? // external file export interface TSomeFunctionArgs { someKey: string // there should also be a type ...

The error message "TypeError: 'undefined' is not an object ('_this.props')" indicates that the property '_this

Having trouble solving this issue. Need assistance with evaluating 'this.props.speciesSelection.modalize' <BarcodeInput speciesSelection={this.props.speciesSelection} species={species[0]} barcode={{ manufacturerValue: ...

Can a unique custom command be designed for the Kendo UI Grid in Angular2?

The built-in commands supported by the KendoUI Grid for Angular2 include: kendoGridAddCommand kendoGridCancelCommand kendoGridEditCommand kendoGridRemoveCommand kendoGridSaveCommand However, I am working on a project that requires a custom command to be ...

Using Angular 6 and Reactive Forms can pose a challenge when attempting to programmatically set the select option while utilizing objects and the [selected

I'm really stuck on this issue. In my Angular project, I have two reactive forms that both contain a select control with options stored in class variables. One form uses basic option strings for employee choices like: ["Dan Smith", "Mark Johnson", e ...

"Utilizing Typescript's keyof operator on its own

I'm grappling with the challenge of creating a type that can utilize the typeof its own keys, but I'm hitting a roadblock. Below is a simplified version of what I'm attempting to achieve: type SpecialType = Record<string, (getter: <K e ...