角度形式输入值未定义

时间:2017-10-30 22:57:54

标签: forms angular typescript angular4-forms

我试图以我的第一个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);    
  }
}

为什么会这样?

2 个答案:

答案 0 :(得分:4)

您需要使用#include "Trie.cpp" #include <iostream> #include <sstream> #include <string> #include <vector> using namespace std; int main(int argc, char* argv[]) { // Initialize trie up here Trie myTrie = *new Trie(); // parse input lines until I find newline for(string line; getline(cin, line) && line.compare(""); ) { stringstream ss(line); string string_weight; ss >> string_weight; int weight = stoi(string_weight); // I am just going to put these words into a vector // you probably want to put them in your trie vector<string> phrase = {}; for(string word; ss >> word;) { phrase.push_back(word); } myTrie.add(phrase, weight); } // parse query line string query; getline(cin, query); cout << myTrie.root.children[0].getWord() << endl; return 0; } 标记输入,因此angular会知道这是表单控件之一:

ngModel

或者您可以先在组件中定义变量,然后通过<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> )就足够了。

答案 1 :(得分:1)

有些人应该这样做..

也许您想了解模型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);
  }
}
相关问题