我正在尝试以我的第一个角度形式获取输入字段的值,但它总是未定义的,我也不知道为什么。我正确地导入了FormsModule,并且我可以很好地引用form对象,所以我肯定遗漏了一些明显的东西。
我的组件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);
}
}你知道为什么会这样吗?
发布于 2017-10-31 07:27:37
你需要用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")就足够了。
发布于 2017-10-31 07:35:56
像这样的一些应该是有效的..
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);
}
}https://stackoverflow.com/questions/47025468
复制相似问题