Angular表单组在提交时未返回结果。

huangapple go评论60阅读模式
英文:

Angular form group not returning on submit

问题

我注意到这里有一个奇怪的问题。 当单击提交按钮时,我的角度表单组没有返回任何内容。 单击后,它也不会在控制台中记录任何内容。 表单本身几乎与我另一个正常工作的表单完全相同。

我尝试删除HTML组件的某些部分,以查看是否会引发问题(下拉菜单因为它调用不同的对象来填充选择字段)。 我还尝试将表单值和表单状态打印到页面上,但它不会更新,只返回[object Object]并保持在无效状态。

我不知道是什么原因导致了这个问题。 我是否在某个地方漏掉了什么?

create-locations.component.ts:

import { Component, OnInit, EventEmitter, Output } from '@angular/core';
import { Clients } from '../../../../_models/clients';
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
import { AlertifyService } from '../../../../_services/alertify.service';
import { ActivatedRoute } from '@angular/router';
import { Locations } from '../../../../_models/locations';
import { LocationService } from '../../../../_services/location.service';

@Component({
  selector: 'app-create-locations',
  templateUrl: './create-locations.component.html',
  styleUrls: ['./create-locations.component.scss']
})
export class CreateLocationsComponent implements OnInit {
  @Output() cancelRegister = new EventEmitter();
  client: Clients[];
  locations: Locations;
  createLocForm: FormGroup;

  constructor(private locationService: LocationService, private alertify: AlertifyService, private fb: FormBuilder,
    private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.data.subscribe(data => {
      this.client = data['clients'].result;
    });
    this.createLocationForm();
  }

  createLocationForm() {
    this.createLocForm = this.fb.group({
      LocationName: new FormControl('', Validators.required),
      ContactFirstName: new FormControl('', [Validators.required]),
      ContactLastName: new FormControl('', Validators.required),
      ContactPhone: new FormControl('', Validators.required),
      StreetAddress: new FormControl('', Validators.required),
      City: new FormControl('', Validators.required),
      State: new FormControl('', Validators.required),
      Country: new FormControl('', Validators.required),
      PostalCode: new FormControl('', Validators.required),
      AssociatedClient: new FormControl('', Validators.required),
      ValidFrom: new FormControl(),
      ValidTo: new FormControl(),
      ClientId: new FormControl()
    });
  }

  createLocation() {
    if (this.createLocForm.valid) {
      this.locations = Object.assign({}, this.createLocForm.value);
      console.log(this.createLocForm.value);
      this.locationService.CreateLocations(this.locations).subscribe(() => {
        this.alertify.success('Registration created successfully');
      }, error => {
        this.alertify.error(error);
      });
    }
  }

  cancel() {
    this.cancelRegister.emit(false);
    console.log('cancelled');
  }
}

create-location.component.html:

<div class="row">
  <div class="col-md-12">
    <div class="card card-user">
      <div class="card-header">
        <h5 class="card-title">Create New Location</h5>
      </div>
      <div class="card-body">
        <form [formGroup]="createLocForm" (ngSubmit)="createLocation()" enctype="multipart/form-data">
          <!-- ... 此处省略了表单的其余部分 ... -->
          <div class="card-footer">
            <button type="submit" class="btn btn-sm btn-primary">
              <i class="fa fa-dot-circle-o"></i> Submit
            </button>
            <button type="reset" class="btn btn-sm btn-danger" (click)="cancel()">
              <i class="fa fa-ban"></i> Cancel
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>
<p>Form Value: {{createLocForm.value | json}}</p>
<p>Form Status: {{createLocForm.status | json}}</p>
英文:

Looking at an odd problem here. My angular form group isn't returning anything when the submit button is clicked. It's also not logging to the console when clicked as well. The form itself is almost identical to another I have that works just fine.

I've tried removing some parts of the html component to see if it was causing an issue (the dropdown as its calling a different object to populate the select field). I've also attempted to print the form value and form status onto the page but it doesn't update and only returns [object Object] and remains in an invalid state.

I'm at a loss as to what is causing this. Have I missed something somewhere?

create-locations.component.ts:

import { Component, OnInit, EventEmitter, Output } from &#39;@angular/core&#39;;
import { Clients } from &#39;../../../../_models/clients&#39;;
import { FormGroup, FormBuilder, FormControl, Validators } from &#39;@angular/forms&#39;;
import { AlertifyService } from &#39;../../../../_services/alertify.service&#39;;
import { ActivatedRoute } from &#39;@angular/router&#39;;
import { Locations } from &#39;../../../../_models/locations&#39;;
import { LocationService } from &#39;../../../../_services/location.service&#39;;
@Component({
selector: &#39;app-create-locations&#39;,
templateUrl: &#39;./create-locations.component.html&#39;,
styleUrls: [&#39;./create-locations.component.scss&#39;]
})
export class CreateLocationsComponent implements OnInit {
@Output() cancelRegister = new EventEmitter();
client: Clients[];
locations: Locations;
createLocForm: FormGroup;
constructor(private locationService: LocationService, private alertify: AlertifyService, private fb: FormBuilder,
private route: ActivatedRoute) { }
ngOnInit() {
this.route.data.subscribe(data =&gt; {
this.client = data[&#39;clients&#39;].result;
});
this.createLocationForm();
}
createLocationForm() {
this.createLocForm = this.fb.group({
LocationName: new FormControl(&#39;&#39;, Validators.required),
ContactFirstName: new FormControl(&#39;&#39;, [Validators.required]),
ContactLastName: new FormControl(&#39;&#39;, Validators.required),
ContactPhone: new FormControl(&#39;&#39;, Validators.required),
StreetAddress: new FormControl(&#39;&#39;, Validators.required),
City: new FormControl(&#39;&#39;, Validators.required),
State: new FormControl(&#39;&#39;, Validators.required),
Country: new FormControl(&#39;&#39;, Validators.required),
PostalCode: new FormControl(&#39;&#39;, Validators.required),
AssociatedClient: new FormControl(&#39;&#39;, Validators.required),
ValidFrom: new FormControl(),
ValidTo: new FormControl(),
ClientId: new FormControl()
});
}
createLocation() {
if (this.createLocForm.valid) {
this.locations = Object.assign({}, this.createLocForm.value);
console.log(this.createLocForm.value);
this.locationService.CreateLocations(this.locations).subscribe(() =&gt; {
this.alertify.success(&#39;Registration created successfully&#39;);
}, error =&gt; {
this.alertify.error(error);
});
}
}
cancel() {
this.cancelRegister.emit(false);
console.log(&#39;cancelled&#39;);
}
}

create-location.component.html:

&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;col-md-12&quot;&gt;
&lt;div class=&quot;card card-user&quot;&gt;
&lt;div class=&quot;card-header&quot;&gt;
&lt;h5 class=&quot;card-title&quot;&gt;Create New Location&lt;/h5&gt;
&lt;/div&gt;
&lt;div class=&quot;card-body&quot;&gt;
&lt;form [formGroup]=&quot;createLocForm&quot;
(ngSubmit)=&quot;createLocation()&quot;
enctype=&quot;multipart/form-data&quot;
&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;col-md-5 pr-1&quot;&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label&gt;Location Name&lt;/label&gt;
&lt;input type=&quot;text&quot;
[ngClass]=&quot;{&#39;is-invalid&#39;: createLocForm.get(&#39;LocationName&#39;).errors &amp;&amp; createLocForm.get(&#39;LocationName&#39;).touched}&quot;
class=&quot;form-control&quot;
formControlName=&quot;LocationName&quot;
placeholder=&quot;Complete Security Ltd.&quot;/&gt;
&lt;div class=&quot;invalid-feedback&quot;&gt;Please enter the location name&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;col-md-3 px-1&quot;&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label&gt;Contact First Name&lt;/label&gt;
&lt;input
type=&quot;text&quot;
[ngClass]=&quot;{&#39;is-invalid&#39;: createLocForm.get(&#39;ContactFirstName&#39;).errors &amp;&amp; createLocForm.get(&#39;ContactFirstName&#39;).touched}&quot;
formControlName=&quot;ContactFirstName&quot;
class=&quot;form-control&quot;
placeholder=&quot;John&quot;
/&gt;
&lt;div class=&quot;invalid-feedback&quot;&gt;Please enter a contact first name&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;col-md-4 pl-1&quot;&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label for=&quot;text&quot;&gt;Contact Last Name&lt;/label&gt;
&lt;input
type=&quot;text&quot;
[ngClass]=&quot;{&#39;is-invalid&#39;: createLocForm.get(&#39;ContactFirstName&#39;).errors &amp;&amp; createLocForm.get(&#39;ContactFirstName&#39;).touched}&quot;
formControlName=&quot;ContactFirstName&quot;
class=&quot;form-control&quot;
placeholder=&quot;Smith&quot;
/&gt;
&lt;div class=&quot;invalid-feedback&quot;&gt;Please enter a contact last name&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;col-md-3 pr-1&quot;&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label&gt;Phone Number&lt;/label&gt;
&lt;input
type=&quot;text&quot;
[ngClass]=&quot;{&#39;is-invalid&#39;: createLocForm.get(&#39;ContactPhone&#39;).errors &amp;&amp; createLocForm.get(&#39;ContactPhone&#39;).touched}&quot;
formControlName=&quot;ContactPhone&quot;
class=&quot;form-control&quot;
placeholder=&quot;604-929-3929&quot;
/&gt;
&lt;div class=&quot;invalid-feedback&quot;&gt;Please enter a phone number&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;col-md-9 pr-1&quot;&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label&gt;Street Address&lt;/label&gt;
&lt;input
type=&quot;text&quot;
[ngClass]=&quot;{&#39;is-invalid&#39;: createLocForm.get(&#39;StreetAddress&#39;).errors &amp;&amp; createLocForm.get(&#39;StreetAddress&#39;).touched}&quot;
formControlName=&quot;StreetAddress&quot;
class=&quot;form-control&quot;
placeholder=&quot;123 Main St&quot;
/&gt;
&lt;div class=&quot;invalid-feedback&quot;&gt;Please enter a street address&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;col-md-3 pr-1&quot;&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label&gt;City&lt;/label&gt;
&lt;input
type=&quot;text&quot;
[ngClass]=&quot;{&#39;is-invalid&#39;: createLocForm.get(&#39;City&#39;).errors &amp;&amp; createLocForm.get(&#39;City&#39;).touched}&quot;
formControlName=&quot;City&quot;
class=&quot;form-control&quot;
placeholder=&quot;North Vanouver&quot;
/&gt;
&lt;div class=&quot;invalid-feedback&quot;&gt;Please enter a city&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;col-md-3 pr-1&quot;&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label&gt;State&lt;/label&gt;
&lt;input
type=&quot;text&quot;
[ngClass]=&quot;{&#39;is-invalid&#39;: createLocForm.get(&#39;State&#39;).errors &amp;&amp; createLocForm.get(&#39;State&#39;).touched}&quot;
formControlName=&quot;State&quot;
class=&quot;form-control&quot;
placeholder=&quot;BC&quot;
/&gt;
&lt;div class=&quot;invalid-feedback&quot;&gt;Please enter a state&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;col-md-3 px-1&quot;&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label&gt;Country&lt;/label&gt;
&lt;input
type=&quot;text&quot;
[ngClass]=&quot;{&#39;is-invalid&#39;: createLocForm.get(&#39;Country&#39;).errors &amp;&amp; createLocForm.get(&#39;Country&#39;).touched}&quot;
formControlName=&quot;Country&quot;
class=&quot;form-control&quot;
placeholder=&quot;Canada&quot;
/&gt;
&lt;div class=&quot;invalid-feedback&quot;&gt;Please enter a country&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;col-md-3 pl-1&quot;&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label&gt;Postal Code&lt;/label&gt;
&lt;input
type=&quot;text&quot;
[ngClass]=&quot;{&#39;is-invalid&#39;: createLocForm.get(&#39;PostalCode&#39;).errors &amp;&amp; createLocForm.get(&#39;PostalCode&#39;).touched}&quot;
formControlName=&quot;PostalCode&quot;
class=&quot;form-control&quot;
placeholder=&quot;V7H 1S6&quot;
/&gt;
&lt;div class=&quot;invalid-feedback&quot;&gt;Please enter a postal code&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;col-md-4 pr-1&quot;&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label&gt;Client&lt;/label&gt;
&lt;select id=&quot;ClientId&quot;
class=&quot;form-control&quot; 
formControlName=&quot;ClientId&quot;&gt;
&lt;option *ngFor=&quot;let client of client&quot; [value]=&quot;client.id&quot;&gt;
{{client.organizationName + &quot; | &quot; + client.username}}
&lt;/option&gt;
&lt;/select&gt;
&lt;div class=&quot;invalid-feedback&quot;&gt;Please select a client&lt;/div&gt;
&lt;/div&gt; 
&lt;/div&gt;
&lt;div class=&quot;col-md-4 pr-1&quot;&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label&gt;Start Date&lt;/label&gt;
&lt;input
formControlName=&quot;ValidFrom&quot;
type=&quot;date&quot;
class=&quot;form-control&quot;
/&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;col-md-4 pr-1&quot;&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label&gt;End Date&lt;/label&gt;
&lt;input
formControlName=&quot;ValidTo&quot;
type=&quot;date&quot;
class=&quot;form-control&quot;
/&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;card-footer&quot;&gt;
&lt;button
type=&quot;submit&quot;
class=&quot;btn btn-sm btn-primary&quot;
&gt;
&lt;i class=&quot;fa fa-dot-circle-o&quot;&gt;&lt;/i&gt; Submit
&lt;/button&gt;
&lt;button
type=&quot;reset&quot;
class=&quot;btn btn-sm btn-danger&quot;
(click)=&quot;cancel()&quot;
&gt;
&lt;i class=&quot;fa fa-ban&quot;&gt;&lt;/i&gt; Cancel
&lt;/button&gt;
&lt;/div&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;Form Value: {{createLocForm.value}} | json&lt;/p&gt;
&lt;p&gt;Form Status: {{createLocForm.status}} | json&lt;/p&gt;

答案1

得分: 2

<button (Click)="createLocation()"
type="submit"
class="btn btn-sm btn-primary"
>
提交

在提交按钮内调用 createLocation() 函数。

英文:
&lt;button (Click)=&quot;createLocation()&quot;
type=&quot;submit&quot;
class=&quot;btn btn-sm btn-primary&quot;
&gt;
&lt;i class=&quot;fa fa-dot-circle-o&quot;&gt;&lt;/i&gt; Submit
&lt;/button&gt;

Call the createLocation() function inside the submit button.

答案2

得分: 1

我找到了一些问题。以下是我的解决方案,希望这对你有所帮助:

对于你的TS组件

createLocation() {
    if (this.createLocForm.valid) {
        this.locations = Object.assign({}, this.createLocForm.value);
        // console.log(this.createLocForm.value);
        this.locationService.CreateLocations()
            .subscribe(data => {
                this.createLocForm.setValue(data);
                console.log(this.createLocForm.value);
                this.alertify.success('Registration created successfully');
            }, error => {
                this.alertify.error(error);
            });
    }
}

解释:

  • 当你将 console.log(this.createLocForm.value) 放在 subscribe 之前时,你会收到 createLocForm.value 为 undefined,因为初始时,createLocForm 没有数据,所以它是 undefined。当你将它放在 subscribe 之后时,如我在上面的示例中所示,“data”属性 将包含该对象。该对象包含来自用户输入的值。“createLocForm.value” 将接收来自 “data”属性 的值。
  • 我认为你不必在服务的 “CreateLocations”方法 中传递 “location属性”。因为当我查看你的HTML模板时,我没有看到你使用 “location属性” 来保存数据。但我可能错了,所以欢迎任何更正。
英文:

I found some of the issues. Here is my solution and I hope this will help you:

> For your TS Component

createLocation() {
if (this.createLocForm.valid) {
this.locations = Object.assign({}, this.createLocForm.value);
// console.log(this.createLocForm.value);
this.locationService.CreateLocations()
.subscribe(data =&gt; {
this.createLocForm.setValue(data);
console.log(this.createLocForm.value); 
this.alertify.success(&#39;Registration created successfully&#39;);
}, error =&gt; {
this.alertify.error(error);
});
}
}

Explanation:

  • When you put the console.log(this.createLocForm.value) before the subscribe, you will receive createLocForm.value as undefined because in the initial, the createLocForm have no data so it is undefined. When you put it after subcribe, the "data" property as you see above in my example will contain the object. This object contains the values from the user input. "createLocForm.value" will receive the values of the from the "data" property.
  • I don't think you have to pass the "location" property to the "CreateLocations" method in your service. Because when I looked at your HTML Template, I did not see you use "location" property to save data. But I may wrong so corrections are all welcome.

答案3

得分: 1

尝试将以下行更改为删除括号?

ContactFirstName: new FormControl('', [Validators.required]),
英文:

Have you try to change the following line by removing the brakets?

ContactFirstName: new FormControl(&#39;&#39;, [Validators.required]),

huangapple
  • 本文由 发表于 2020年1月4日 12:24:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/59587868.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定