我正在创建基本的角度形式,并onsubmit
尝试检索表单值,但是我的情况不是获取值而是作为对象获得值。
注意:通过一些示例复制了代码。
你可以告诉我为什么我会得到对象而不是价值吗?请找到我的以下代码:
HTML:
<div class="container">
<h2> User Data </h2>
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm.value)">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" ngModel>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" ngModel>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
成分:
onSubmit(value: any) {
console.log("Form Value : " + value);
}
答案 0 :(得分:0)
该值必须是一个对象。表单包含多个元素,因此具有多个值。
试试这个:
onSubmit(value: any) {
console.log("Form Value : ",value);
console.log(value.name);
console.log(value.email);
}
答案 1 :(得分:0)
您的输入字段应如下所示:
<input class="form-control" type="text" [(ngModel)]="name" formControlName="name">
然后在提交功能中获取它的值
onSubmit(post){
console.log(post.name);
}
答案 2 :(得分:0)
您的userForm.value
包含name
和email
两个值。
所以,当你执行console.log(userForm.value);
时,它会返回如下内容:
{
name: 'Surjeet',
email: 'suri@yopmail.com'
}
要访问您可以执行的特定值:
userForm.value.name
=&gt;它将返回&#39; Surjeet&#39; userForm.value.email
=&gt;它将返回&#39; suri@yopmail.com' 那么你现在可以做什么:
Two things you can do in your case:
第一个 :(通过其属性获取值)
onSubmit(value: any) {
//get the value by its property
console.log("Name: " + value.name);
console.log("Email: " + value.email);
}
第二个 :(仅传递您需要的值)
//(ngSubmit)=&#34;的onSubmit(userForm.value.name)&#34;
<div class="container">
<h2> User Data </h2>
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm.value.name)">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" ngModel>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" ngModel>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
答案 3 :(得分:0)
--> in HTML file
<div class="container">
<h2> User Data </h2>
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm.value.name,userForm.value.email)">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" ngModel>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" ngModel>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
--> in TS file
onSubmit(name:any, email:any) {
console.log('Name = ' + name);
console.log('Email = ' + email);
}
--> By this code you can get specific value in form either by button triggering (should mention required properties to submit and also in receiving method) or by entire form submit.