我试图在我的第一个 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);
}
}
知道这是为什么吗?
最佳答案
您需要用 ngModel
标记输入,这样 angular 就会知道这是表单的控件之一:
<input type="text" ngModel name="q" placeholder="search">
或者您可以先在组件中定义变量,然后通过 [(ngModel)]
指令将输入绑定(bind)到它:
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>
如果您只想从输入中读取值,一种绑定(bind)方式(只需 [ngModel]="q"
)就足够了。
关于forms - Angular 形式输入值未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47025468/