If an Angular reactive form component has a particular value

I am working with a group of radio buttons. When a user chooses the option "yes," I would like to display an additional input box on the form.

Link to Code Example

HTML.component

<div formGroupName="radioButtonsGroup" class="form-group col-6 pl-0 pt-3">

    <div class="form-check-inline" *ngFor="let item of personal.radioButtonsdata">
        <label for="{{item.section}}" class="col-12 customradio"
            ><span>{{item.section}}</span>
            <input [value]="item" id="{{item.section}}" type="radio" formControlName="selectedButton"/>
            <span class="checkmark"></span>
        </label>
    </div>

  <div class="col-md-8" > // Updated section for displaying input based on selected value
        <input type="text" formControlName="title" class="form-control" placeholder="Title">
</div>
  
</div>

If anyone can help me troubleshoot why this is not functioning as desired, I would greatly appreciate it!

Answer №2

In the template, all content is interpreted based on the related class (or template variables), which means you must call the JavaScript control in this manner:

*ngIf="form.controls['selectedButton'].value === 'yes'"

Answer №3

Utilize a function to set a flag based on the value of a radio button,

(ngModelChange)="onRadiochange($event)"

Follow this example:

View Working Demo

.html

<input [value]="item" (ngModelChange)="onRadiochange($event)" id="{{item.section}}" type="radio" formControlName="selectedButton" />

<div class="col-md-8" *ngIf="showTitle">
        <input type="text" formControlName="title"   class="form-control" placeholder="Title">
</div>

.ts

  onRadiochange(e) {
    if(e.section == 'yes'){
      this.showTitle = true
    } else {
      this.showTitle = false
    }
  }

This can also be achieved in one line like so:

<input [value]="item" (ngModelChange)="$event.section == 'yes' ? showTitle=true:showTitle=false" id="{{item.section}}" type="radio" formControlName="selectedButton" />

Answer №4

If the "yes" checkbox is checked, then you should make sure to display the title textbox.
To achieve this functionality, modify your code as follows:

Firstly, in the personal.component.ts file, include the following variable:

yesSelected: boolean = true;

Additionally, within the ngOnInit() function, add the following logic:

this.form.valueChanges.subscribe(val => {
      if (val.radioButtonsGroup.selectedButton.section === "yes") 
         this.yesSelected = true;
      else 
         this.yesSelected = false;
});

In the personal.component.html file, update your if condition like so:

<div class="col-md-8" *ngIf="yesSelected">
      <input type="text" formControlName="title" placeholder="Title">
</div>

By implementing these changes, the title textbox will be displayed only when the "yes" checkbox is selected.

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

[Vue alert]: "Maximum" property or method is not declared in the instance but is being referenced during the rendering process

Here is my custom Vue component: Vue.component("product-list", { props: ["products", "maximum-price"], template: ` <div> <div class="row d-flex mb-3 align-items-center p-3 rounded-3 animate__animate ...

Chrome is experiencing a problem with anchor tags that have an href attribute set to a "blob:" URL and using a target of "_blank"

My current project involves developing a website feature that allows users to download a PDF version of a page. To achieve this, the generated HTML is rendered into a PDF on the server, which is then returned as a Base64-encoded PDF. This data is converted ...

What is the best way to symbolize a breadcrumb offspring?

In my table representation, the breadcrumb is shown as: <ol class="breadcrumb" data-sly-use.breadcrumb="myModel.js"> <output data-sly-unwrap data-sly-list="${breadcrumb}"> <li itemscope itemtype="http://data-vocabulary.org/ ...

Could someone please explain why my ajax is not functioning properly?

I have been working on an AJAX function to pass input values from one page to another. However, I am facing a challenge where the value is not being passed as expected after redirection. Despite my efforts, I cannot figure out why it's not functionin ...

Top method for stacking several divs in a vertical line

In search of the most effective method for organizing numerous dynamically generated divs (all with identical widths) in a vertical stack, two potential solutions have emerged: Utilize float:left... Implement an unordered list and enclose each div within ...

What is the best way to create a summary module that consolidates and re-exports all the exported functionalities from multiple sub-modules in E

Is there a way to re-export the exports from multiple files in an ESM module without manually listing each export? I am looking to convert my CommonJS module directory, which contains several files, to ESM imports/exports. Currently, I have an index.js fi ...

Finding the source of the err.kind expression in the MERN stack: Unraveling the mystery

Recently, I've been delving into the world of MERN stack development and came across an interesting technique for Error Handling in a tutorial. The tutorial showcased various expressions that can be used to identify different types of errors being thr ...

Error in TypeScript: Objects can only specify properties that are known, and 'state' is not found in type 'Partial<Path>'

As I strive to pass props through a React Router Link, my goal is to include all the user props. The code below is causing an error, particularly where state: {...employee} is highlighted. Although I am relatively new to TypeScript, I am actively working ...

Toggle button with v-bind in Nativescript Vue

Hey there, I'm just starting out with nativescript vue and I have a question regarding a simple "toggle" feature that I'm trying to implement. Essentially, when a button is pressed, I want the background color to change. <template> < ...

Tips for successfully transferring values or parameters within the Bootstrap modal

How can I create a cancel button that triggers a modal asking "Are you sure you want to cancel the task?" and calls a function to make an API call when the user clicks "Ok"? The challenge is each user has a unique ID that needs to be passed to the API for ...

Restricting the input on a React component to only accept alphabet characters from A to Z instead of allowing any keyboard

I am currently facing a challenge with understanding a specific component, particularly the allowForClassification value. This boolean value is passed down to a child component and decides whether a button is displayed or not. The issue arises when tryin ...

Pass the form data to a Bootstrap modal upon submission of the form

I'm attempting to retrieve form data and convert it to JSON to display in a modal dialog that opens on the Submit button click! This is my progress so far: HTML <form class="form-horizontal" id="configuration-form"> --irrelevant-- <button ...

Insert elements to an XML document in Node.js using libxmljs

I've been working on updating an XML file by adding a new child node using the code below: var libxml = require('libxmljs'); var xml = '<?xml version="1.0" encoding="UTF-8"?>' + '<root>' + ...

The concept of overloaded function types in TypeScript

Is it possible to create an overloaded function type without specifying a concrete function? By examining the type of an overloaded function, it appears that using multiple call signatures on an interface or object type is the recommended approach: functi ...

When converting a PDF to a PNG, the precious data often disappears in the process

I am currently facing a problem with the conversion of PDF to PNG images for my application. I am utilizing the pdfjs-dist library and NodeCanvasFactory functionality, but encountering data loss post-conversion. class NodeCanvasFactory { create(w, h) { ...

Accessing files from various directories within my project

I'm working on a project with 2 sources and I need to import a file from MyProject into nest-project-payment. Can you please guide me on how to do this? Here is the current file structure of my project: https://i.stack.imgur.com/KGKnp.png I attempt ...

What is the best way to recycle a single modal in Ionic?

Apologies for the vague title, but I'm facing an issue with creating a single modal to display data from multiple clickable elements, rather than having separate modals for each element. For example, when I click on item 1, its data should be shown in ...

Having trouble accessing undefined properties in ReactJs? Specifically, encountering issues when trying to read the property "name"?

I am facing an issue with using the data in my console even though I can log it. The structure of my data object is as follows: {_id: '616bf82d16a2951e53f10da4', name: 'abd', email: '[email protected]', phone: '123456789 ...

Is it the correct method to query names within JavaScript arrays?

I am looking to create a dynamic list view using React JS without relying on any pre-built components. My goal is to incorporate a basic search function that can find users by their names, and I need to address this issue... For example, I have drafted th ...

Modifying the Vue.js Vue3-slider component for custom color schemes

Currently, I am using the vue-slider component and would like to customize the color of the slider itself. The specific class that needs to be styled is "vue-slider-dot-tooltip-inner". Below is a screenshot displaying the original CSS styling for vue-slid ...