Search code examples
javascriptangulartypescriptradio-button

angular 6 ngModel with radio button not passing any data


I'd like to link radio buttons inside a form to an object, i cant get it to work!

I am linking ngModel to a variable of type string that is called presentation

I dont know what am I missing? even when i copy a working example it wont work in my form!

here is part of my form that I think is dysfunctional: HTML:

<div class="uk-margin-large-right">

  <div class="uk-flex-inline ">
    <span class="uk-form-label uk-margin-small-right uk-text-bold "> Presentation </span>
    <label  class="uk-margin-medium-right">
      <input class="uk-radio " type="radio" name="radio1" value="Cephalic" [(ngModel)]="presentaion"> Cephalic  </label>
    <label class="uk-margin-medium-right">
      <input class="uk-radio" type="radio" name="radio1" value="Breech" [(ngModel)]="presentaion"> Breech </label>
      <label class="uk-margin-medium-right">
        <input class="uk-radio" type="radio" name="radio1" value="Transverse lie" [(ngModel)]="presentaion"> Transverse lie </label>

  </div>
  <p>this is {{presentation}}</p>
</div>

Typescript:

    import { Component, OnInit } from '@angular/core';
import { CommService } from '../services/comm.service';



@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {


  user = {
    Doctor: '',
    Patient: '',
    Type:'',
    Report: ''
  };

  presentation:'';


  constructor(private CommService: CommService) { }

  ngOnInit() {
    this.CommService.setData(this.user);
    console.log(this.presentation);
  }

}

Solution

  • Declare it like this if you want to give it initial value

      presentaion:string = 'Cephalic';
    
      log() {  // log the value to console
        console.log(this.presentaion)
      }
    

    Template

       <p>this is {{presentaion}}</p>
       <button (click)="log()">Log the value to console</button>
    

    in your example there was a typo with the property name <p>this is {{presentation}}</p> just change it to presentaion

    stackblitz example