英文:
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 '@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="row">
<div class="col-md-5 pr-1">
<div class="form-group">
<label>Location Name</label>
<input type="text"
[ngClass]="{'is-invalid': createLocForm.get('LocationName').errors && createLocForm.get('LocationName').touched}"
class="form-control"
formControlName="LocationName"
placeholder="Complete Security Ltd."/>
<div class="invalid-feedback">Please enter the location name</div>
</div>
</div>
<div class="col-md-3 px-1">
<div class="form-group">
<label>Contact First Name</label>
<input
type="text"
[ngClass]="{'is-invalid': createLocForm.get('ContactFirstName').errors && createLocForm.get('ContactFirstName').touched}"
formControlName="ContactFirstName"
class="form-control"
placeholder="John"
/>
<div class="invalid-feedback">Please enter a contact first name</div>
</div>
</div>
<div class="col-md-4 pl-1">
<div class="form-group">
<label for="text">Contact Last Name</label>
<input
type="text"
[ngClass]="{'is-invalid': createLocForm.get('ContactFirstName').errors && createLocForm.get('ContactFirstName').touched}"
formControlName="ContactFirstName"
class="form-control"
placeholder="Smith"
/>
<div class="invalid-feedback">Please enter a contact last name</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-3 pr-1">
<div class="form-group">
<label>Phone Number</label>
<input
type="text"
[ngClass]="{'is-invalid': createLocForm.get('ContactPhone').errors && createLocForm.get('ContactPhone').touched}"
formControlName="ContactPhone"
class="form-control"
placeholder="604-929-3929"
/>
<div class="invalid-feedback">Please enter a phone number</div>
</div>
</div>
<div class="col-md-9 pr-1">
<div class="form-group">
<label>Street Address</label>
<input
type="text"
[ngClass]="{'is-invalid': createLocForm.get('StreetAddress').errors && createLocForm.get('StreetAddress').touched}"
formControlName="StreetAddress"
class="form-control"
placeholder="123 Main St"
/>
<div class="invalid-feedback">Please enter a street address</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-3 pr-1">
<div class="form-group">
<label>City</label>
<input
type="text"
[ngClass]="{'is-invalid': createLocForm.get('City').errors && createLocForm.get('City').touched}"
formControlName="City"
class="form-control"
placeholder="North Vanouver"
/>
<div class="invalid-feedback">Please enter a city</div>
</div>
</div>
<div class="col-md-3 pr-1">
<div class="form-group">
<label>State</label>
<input
type="text"
[ngClass]="{'is-invalid': createLocForm.get('State').errors && createLocForm.get('State').touched}"
formControlName="State"
class="form-control"
placeholder="BC"
/>
<div class="invalid-feedback">Please enter a state</div>
</div>
</div>
<div class="col-md-3 px-1">
<div class="form-group">
<label>Country</label>
<input
type="text"
[ngClass]="{'is-invalid': createLocForm.get('Country').errors && createLocForm.get('Country').touched}"
formControlName="Country"
class="form-control"
placeholder="Canada"
/>
<div class="invalid-feedback">Please enter a country</div>
</div>
</div>
<div class="col-md-3 pl-1">
<div class="form-group">
<label>Postal Code</label>
<input
type="text"
[ngClass]="{'is-invalid': createLocForm.get('PostalCode').errors && createLocForm.get('PostalCode').touched}"
formControlName="PostalCode"
class="form-control"
placeholder="V7H 1S6"
/>
<div class="invalid-feedback">Please enter a postal code</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 pr-1">
<div class="form-group">
<label>Client</label>
<select id="ClientId"
class="form-control"
formControlName="ClientId">
<option *ngFor="let client of client" [value]="client.id">
{{client.organizationName + " | " + client.username}}
</option>
</select>
<div class="invalid-feedback">Please select a client</div>
</div>
</div>
<div class="col-md-4 pr-1">
<div class="form-group">
<label>Start Date</label>
<input
formControlName="ValidFrom"
type="date"
class="form-control"
/>
</div>
</div>
<div class="col-md-4 pr-1">
<div class="form-group">
<label>End Date</label>
<input
formControlName="ValidTo"
type="date"
class="form-control"
/>
</div>
</div>
</div>
<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>
答案1
得分: 2
<button (Click)="createLocation()"
type="submit"
class="btn btn-sm btn-primary"
>
提交
在提交按钮内调用 createLocation() 函数。
英文:
<button (Click)="createLocation()"
type="submit"
class="btn btn-sm btn-primary"
>
<i class="fa fa-dot-circle-o"></i> Submit
</button>
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 => {
this.createLocForm.setValue(data);
console.log(this.createLocForm.value);
this.alertify.success('Registration created successfully');
}, error => {
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('', [Validators.required]),
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论