Angular 表单不传递来自 HTML 的数据

Angular Forms not passing data from HTML

我似乎无法将输入数据从 HTML 的 <select> 元素传递到 Angular 表单本身。

首先是我的代码。

文件名: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>

文件名: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() {}

}

附加信息:

@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

预期输出(来自 console.log):

Object
    pasteSyntax: "plain"

当前输出(来自console.log):

Object
    pasteSyntax: null

谁能告诉我哪里出错了或者我使用了错误的语法?

您的问题是 addPaste:

中的这一行
this.pasteSyntax = paste.syntax;

应该是:

this.pasteSyntax = paste.pasteSyntax;

但正如 Nilandri 所提到的,您不需要变量,您可以使用模板中的表单访问值,或者在提交时打印 pasteSyntax 属性以 rForm.value 作为参数的形式:

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

DEMO