Error with property checked and value in Angular

1

I'm trying to use a code to get the value of the selected radio button and I'm encountering the following errors:

  

The 'checked' property does not exist in type 'HTMLElement'.

  

The 'value' property does not exist in the NodeListOf type.

Follow my code:

getRadioValor(name){
  var rads = document.getElementsByName(name);

  for(var i = 0; i< rads.length; i++){
    if(rads[i].checked){
      return rads.value;
    }
  }
}

What is the reason for these errors? And how to solve?

    
asked by anonymous 09.11.2018 / 02:57

2 answers

0

A simple way I use to get the value checked from radio s with same name in pure Javascript is like this:

getRadioValor(name){
  const radioValue = document.querySelector('input[name = ${name}]:checked').value;
  console.log(radioValue);
}

Since you are using angular-material you should do in event change of <mat-radio-button> , like this:

<mat-radio-button nome="R0" class="margem" value="1" (change)="getRadioValor($event)"
  0
</mat-radio-button>

And the method looks like this:

getRadioValor(event) {
 console.log(event.value)
}
    
09.11.2018 / 13:47
0
  

The 'checked' property does not exist in type 'HTMLElement'.

It means that the name you passed did not return elements of type radio or checkbox (they are the ones containing the checked property). Make sure there are no other elements with the same name.

  

The 'value' property does not exist in type NodeListOf.

You forgot [i] to access a NodeList element and ended up trying to access the value property of NodeList instead of HTMLElement. Just change:

return rads.value;

To:

return rads[i].value;

Here is a working example:

function getRadioValue(name) {
  let radios = document.querySelectorAll('input[name=${name}]');
  
  for (let i=0, l=radios.length ; i<l ; i++) {
    let radio = radios[i];
    
    if (radio.checked) return radio.value;
  }
  
}


let btn = document.querySelector('#btn');

btn.addEventListener('click', () => {
  console.log(getRadioValue('teste'));
});
<label>
  <input type="radio" name="teste" value="1">
  Radio 1
</label>

<label>
  <input type="radio" name="teste" value="2">
  Radio 2
</label>

<label>
  <input type="radio" name="teste" value="3">
  Radio 3
</label>

<br>

<button id="btn">Log selected</button>
    
09.11.2018 / 20:36