angular - 角度形式设置正确但未传递形式值
问题描述
我在我的 html 中定义了以下表单:
<div class="col-12 mt-2">
<form (ngSubmit)="addswingtype()" #addswingtypeform="ngForm">
<div class="row">
<div class="col-10 mt-2">
<input type="text"
id="addswingtype"
name="addswing"
ngModel
placeholder="Enter A Swing Type"
class="form-control">
</div>
<div class="col-2 mt-2">
<button type="submit" class="btn btn-outline-dark">Submit</button>
</div>
</div>
</form>
</div>
然后在我的 ts 文件中添加以下内容:
import {Component, OnInit, ViewChild} from '@angular/core';
import {NgForm} from '@angular/forms';
@ViewChild('addswingtypeform') addswingtypeform:NgForm;
@Component({
selector: 'app-swingerandhosttypes',
templateUrl: './swingerandhosttypes.component.html',
styleUrls: ['./swingerandhosttypes.component.css'],
providers: [Httpservice]
})
export class SwingerandhosttypesComponent implements OnInit {
constructor(private http: Httpservice) { }
addswingtype(){
console.log(this.addswingtypeform);
const url = swingtypeallorcreate;
const payload = {
name: this.addswingtypeform.form.value.addswing
};
this.http.post(url, payload)
.subscribe(
(req: any)=>{
this.swingtypes.push(req);
}
);
}
看起来像正确的代码吗?好吧,因为它似乎是正确的代码。事实上,它与我编写的另一个有效的组件相同。
但无论出于何种原因, the 的addswing
值addswingtypeform
始终是未定义的
我不知道为什么。
是否有任何可能出现问题的线索?
解决方案
请将您的代码更改为以下内容,您可以看到结果。
请用以下代码块替换您的 HTML 代码。
<div class="col-12 mt-2">
<form (ngSubmit)="addswingtype()" #addswingtypeform="ngForm">
<div class="row">
<div class="col-10 mt-2">
<input type="text"
id="addswingtype"
name="addswing"
ngModel
placeholder="Enter A Swing Type"
class="form-control">
</div>
<div class="col-2 mt-2">
<button type="submit" class="btn btn-outline-dark">Submit</button>
</div>
</div>
并通过以下代码块替换您的 TS 代码。
import {Component, OnInit, ViewChild} from '@angular/core';
import {NgForm} from '@angular/forms';
@Component({
selector: 'app-swingerandhosttypes',
templateUrl: './swingerandhosttypes.component.html',
styleUrls: ['./swingerandhosttypes.component.css'],
providers: [Httpservice]
})
export class SwingerandhosttypesComponent implements OnInit {
@ViewChild('addswingtypeform') addswingtypeform:NgForm;
constructor(private http: Httpservice) { }
addswingtype(){
console.log(this.addswingtypeform);
const url = swingtypeallorcreate;
const payload = {
name: this.addswingtypeform.form.value.addswing
};
this.http.post(url, payload)
.subscribe(
(req: any)=>{
this.swingtypes.push(req);
});
}
推荐阅读
- ruby-on-rails - Rails:仅更新实体的某些属性
- list - 无法在新 GCE 虚拟机上列出服务帐户
- c# - 如何通过将 HttpClient 请求转换为 RestSharp 请求来上传文档?
- c - 我将如何阅读并将此文本文件的信息分成数组?
- c++ - 重载矩阵类的加法和乘法运算符
- javascript - 如何在javascript中获取URL中使用where条件?
- python - 为什么 TypeError 即使它需要 2 个参数
- html - 我正在尝试使用媒体查询任何建议来调整我的背景大小
- makefile - 如何从不重建已经构建的目标
- node.js - 从 CDK 访问存储在秘密管理器中的字符串