Edwin Martinez
Edwin Martinez

Reputation: 61

formControlName gives me a null value - Angular

i keep getting a null value from my reactive form. The field name is "from"

my ts file

  ngOnInit() {
this.createForm = new FormGroup({
  'title': new FormControl(null, [
            Validators.required,
            Validators.maxLength(40)
          ]),
  'message': new FormControl(null, [
            Validators.required,
            Validators.maxLength(130)
          ]),
  'from': new FormControl(null,
            Validators.maxLength(40)
          )
});

}

my form

<form [formGroup]="createForm" (ngSubmit)="onSubmit()">
  <div class="form-group">
    <label for="">Food Item</label>
    <input type="text"
          class="form-control"
          placeholder="Bacon Egg & Cheese Sandwich"
          maxlength="40"
          formControlName="title"
      >
  </div>
  <div class="form-group">
    <label for="">Customer Message to Recepient</label>
    <textarea         
        class="form-control"
        rows="4"
        maxlength="130"
        formControlName="message"></textarea>
  </div>
  <div class="form-group">
      <label for="">Customers Name</label><br>
      <input type="text"
      class="form-control"
      placeholder="Anonymous"
      maxlength="40"
      formControlName="from"
      >
      <small class="text-muted">Leave Blank for Anonymous</small>
  </div>
  <button class="btn btn-success">Create</button>
</form>

in my onSubmit() method, this.createForm.controls['from'].value keeps giving me a null

anyone know what i'm doing wrong?

Upvotes: 2

Views: 5875

Answers (1)

Edwin Martinez
Edwin Martinez

Reputation: 61

i found what was wrong. i was expecting an empty string but instead i got null. I was basing my logic on an empty string when i should have based in on null.

The reactive form was doing exactly what it was supposed to.

Upvotes: 1

Related Questions