Etosticity
Etosticity

Reputation: 237

Angular Forms not passing data from HTML

I seem to have a problem passing input data from HTML's <select> element to Angular Forms itself.

Here's my code first.

Filename: home-page.component.html

<form [formGroup]="rForm" (ngSubmit)="addPaste(rForm.value)">

    ...

    <div class="input-field col s12">
        <select formControlName="pasteSyntax">
            <option *ngFor="let choices of pasteSyntaxChoices" [value]="choices.value">{{ choices.text }}</option>
        </select>
        <label>Syntax Highlighting</label>
    </div>

    ...

</form>

Filename: home-page.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
    selector: 'app-home-page',
    templateUrl: './home-page.component.html',
    styleUrls: ['./home-page.component.css']
})

export class HomePageComponent implements OnInit {

    rForm: FormGroup;
    paste: any;

    ...

    pasteSyntax: string = '';

    ...

    pasteSyntaxChoices = [
        { value: "plain", text: "Plain Text" },
        { value: "html", text: "HTML" },
        { value: "css", text: "CSS" },
        { value: "js", text: "JavaScript" },
        { value: "php", text: "PHP" },
        { value: "perl", text: "Perl" },
        { value: "go", text: "Go (Golang)" }
    ];

    constructor(private fb: FormBuilder) {
        this.rForm = fb.group({

            ...

            'pasteSyntax': [null, Validators.required]

            ...

        });
    }

    addPaste(paste) {

        ...

        this.pasteSyntax = paste.syntax;

        ...

        console.log(paste);
    }

    ngOnInit() {}

}

Additional Info:

@angular/animations: 4.2.4
@angular/common: 4.2.4
@angular/compiler: 4.2.4
@angular/core: 4.2.4
@angular/forms: 4.2.4
@angular/http: 4.2.4
@angular/platform-browser: 4.2.4
@angular/platform-browser-dynamic: 4.2.4
@angular/router: 4.2.4
core-js: 2.4.1
rxjs: 5.4.2
zone.js: 0.8.14

Expected Output (From console.log):

Object
    pasteSyntax: "plain"

Current Output (From console.log):

Object
    pasteSyntax: null

Can anyone tell me where did I go wrong or did I use the wrong syntax?

Upvotes: 1

Views: 465

Answers (1)

AVJT82
AVJT82

Reputation: 73357

You problem is this line in your addPaste:

this.pasteSyntax = paste.syntax;

it should be:

this.pasteSyntax = paste.pasteSyntax;

But as mentioned by Nilandri, you don't need to variable, you can access the value from the form in your template with, or then print the pasteSyntax property when you submit your form with rForm.value as parameter:

addPaste(value) {
  console.log(value.pasteSyntax);
  console.log(this.rForm.get('pasteSyntax').value);
  // or
  console.log(this.rForm.controls.pasteSyntax.value)
}

DEMO

Upvotes: 1

Related Questions