gpt4 book ai didi

javascript - Angular Forms 不从 HTML 传递数据

转载 作者:行者123 更新时间:2023-11-30 21:01:57 25 4
gpt4 key购买 nike

我似乎在从 HTML 的 <select> 传递输入数据时遇到问题元素到 Angular Forms 本身。

首先是我的代码。

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

关于javascript - Angular Forms 不从 HTML 传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47047123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com