【问题标题】:Angular form input value undefined角度表单输入值未定义
【发布时间】:2018-04-12 00:51:35
【问题描述】:

我试图在我的第一个 Angular 表单中获取输入字段的值,但它总是未定义,我不知道为什么。我正确地导入了 FormsModule,并且可以很好地引用表单对象,所以我肯定遗漏了一些明显的东西。

我的组件 HTML

<form #searchValue='ngForm' class="" (ngSubmit)='submitSearch(searchValue)'>
  <div>
    <input type="text" name="q" placeholder="search">
  </div>
</form>

还有我的组件 ts 方法(缩短)

import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';

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

export class GoogleComponent implements OnInit {

  constructor() { }

  ngOnInit() {

  }

  submitSearch(formData) {
    console.log(this.searching);
    console.log(formData.value.q);    
  }
}

有什么想法吗?

【问题讨论】:

  • 您将提交表单的 html 元素放在哪里?

标签: forms angular typescript angular4-forms


【解决方案1】:

您需要使用ngModel 标记输入,以便 Angular 知道这是表单的控件之一:

<input type="text" ngModel name="q" placeholder="search">

或者你可以先在你的组件中定义变量,然后通过[(ngModel)]指令将输入绑定到它:

export class GoogleComponent implements OnInit {
  q: string;

  submitSearch() {
    console.log(this.q);
  }
}

<form class="" (ngSubmit)='submitSearch()'>
  <div>
    <input type="text" name="q" [(ngModel)]="q" placeholder="search">
  </div>
</form>

如果您只想从输入中读取值,单向绑定(仅[ngModel]="q")就足够了。

【讨论】:

  • 认为,在发布此内容之前,我确实尝试了您的第二个选项,声明 q 变量是我缺少的部分。感谢您的宝贵时间和直截了当的解释。
【解决方案2】:

这样的一些应该可以工作..

也许您想了解型号 bindingforms

html 组件

<form #searchValue='ngForm' class="some-css-class" (ngSubmit)='submitSearch()'>
  <div>
    <input type="text" name="q" [(ngModel)]="searchValue" placeholder="search">
    <input type="submit" name="btn" placeholder="Submit">
  </div>
</form>

component.ts

import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';

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

export class GoogleComponent implements OnInit {

  searchValue: string = '';

  constructor() { }

  ngOnInit() { }

  submitSearch() {
    console.log(this.searchValue);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    • 2021-04-28
    相关资源
    最近更新 更多