首页 > 解决方案 > 角度形式设置正确但未传递形式值

问题描述

我在我的 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 的addswingaddswingtypeform始终是未定义的

我不知道为什么。

是否有任何可能出现问题的线索?

标签: angularformstypescript

解决方案


请将您的代码更改为以下内容,您可以看到结果。

请用以下代码块替换您的 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);
     });
  }

推荐阅读