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

methods to add an object to formData in vuejs

I am having trouble appending an object to FormData using Axios. I do not want to send data by JSON.stringify() data () { return { product: { title: '', description: '', properties: { ...

ways of exporting and using arrays in Node.js

Constantly receiving the "undefined" error in main.js: var dbAccess = require('../dao/dbAccess'); dbaInstance = new dbAccess(); var wordPool = dbaInstance.getWordPool(); console.log (wordPool); The contents of "dbAccess.js" are as follows: var ...

Creating MySQL query results in Node.js manufacturing process

I am looking to format the MySQL result in Node.js in a specific way. The desired result format should look like this: [ { "m_idx" :1 , "contents" : { "m_name" : "a", ...

Discover the art of concurrently listening to both an event and a timer in JavaScript

Upon loading the page, a timer with an unpredictable duration initiates. I aim to activate certain actions when the countdown ends and the user presses a button. Note: The action will only commence if both conditions are met simultaneously. Note 2: To cl ...

Obtain a Compilation of Video Sources in an HTML5 Format

Hey there, I am using an HTML5 video. This is just an example <video width="320" id="video" height="240" controls> <source src="video.mp4" type="video/mp4"> <source src="video1.mp4" type="video/mp4"> <source src="movie.ogg" typ ...

What is the best way to manage optional peer dependency types while releasing a TypeScript package?

I'm trying to figure out the best way to handle optional peer dependencies when publishing a TypeScript package on npm. My package provides a function that can accept input from either one of two peer dependencies. How should I define these optional p ...

Tips for persisting objects created in PHP while utilizing XMLHttpRequest

Currently, I am working on a web page with the index.php file structured as shown below: include('UserClass.php'); include('html/top.php'); $user = new User(); if (isset($_POST['user'], $_POST['pass'])) { $user-& ...

Encountering error code 2064 without any clear explanation in sight

Hey, I'm currently facing an issue while uploading values to a MySQL table from Node.js. The error 1064 keeps popping up, indicating that the query is badly formatted. However, I can't seem to pinpoint the exact problem. Here's the query in ...

initial render results in undefined data

function Story() { let { id } = useParams(); const pin = useSelector(state => state.pins.pin); const dispatch = useDispatch(); const userid = 2 useEffect(() => { dispatch(getPin(id)); }, [dispatch, id]); return ( <div classN ...

Display complete information of the selected list in a modal window by clicking on it in PHP Yii

I recently started working with the Yii framework and encountered a challenge when trying to pass data from a list to a modal using AJAX. The modal is located within the same view as the list. Here's a snippet of my code: This is my view: <div id ...

Utilize the power of REACT JS to transform a specific segment within a paragraph into a hyperlink. Take advantage of the click event on that hyperlink to execute an API request prior to

In React JSX, I'm encountering an issue trying to dynamically convert a section of text into an anchor tag. Additionally, upon clicking the anchor tag, I need to make an API call before redirecting it to the requested page. Despite my attempts, I have ...

Is there a way to eliminate get variables and filename from a URL using JavaScript or jQuery?

I've been researching this issue, but unfortunately, I haven't been able to find a definitive solution for my specific needs. Let's say I have a URL like... How can I extract this URL and remove the "index.php?search=my+search" part so that ...

I encountered an error while trying to synchronize my Redux state with the component state

Upon clicking the advanced sports search button, I need to display a drawer containing my API values. Currently, when mapping my Redux state with component state, an error is occurring stating "Actions must be plain objects. Use custom middleware for async ...

What is the best way to access the camera of a mobile phone through a web application?

Whenever I try to access the camera on my mobile device through a web app, I encounter an issue. While the camera works perfectly fine on the web version, it fails to show up on my mobile device unless I add https:// in the URL. How can I resolve this prob ...

Tips on saving checklist values as an array within an object using AngularJS

I need help with storing selected checklist items as an array in a separate object. I want to only store the names of the checklist items, but I am struggling to figure out how to achieve this. Below is the HTML code: <div ng-app="editorApp" ng-contro ...

Having trouble accessing the iframe element in an Angular controller through a directive

My webpage contains an iframe with a frequently changing ng-src attribute. I need to execute a function in my controller each time the iframe's src changes, but only after the iframe is fully loaded. Additionally, I require the iframe DOM element to b ...

A guide on seamlessly transitioning from a mobile website to the corresponding native app

I am currently working on a mobile website project. This website is built using basic HTML and is accessed through a URL on a web browser, not as a native app or through PhoneGap. The client has requested links to their Facebook, Pinterest, YouTube, Twitt ...

Adding a fresh element and removing the initial item from a collection of Objects in JavaScript

I'm working on creating an array of objects that always has a length of five. I want to push five objects initially, and once the array reaches a length of five, I need to pop the first object and push a new object onto the same array. This process sh ...

Set the title attribute according to the content of the <p> tag

Recently, I encountered a situation where I had numerous p tags with a specific class (let's call it .text). My task was to include the title attribute containing the text of each tag. For example: <p> Hello, world </p> This would resul ...

Anticipate the completion of Subject callback execution

Take a look at the code snippet below: const mA = async () => { try { const subscription = myEmitter.subscribe(url => getD(url)); const la=()=>{...}; return la; } catch (error) { throw error; } }; ...