要提交表单的一部分而不是整个表单,可以使用Angular的Reactive Forms来实现。以下是一个示例代码:
首先,创建一个包含表单控件的表单组件。
app.component.html:
app.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
myForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.myForm = this.fb.group({
firstName: '',
lastName: '',
email: ''
});
}
onSubmit() {
console.log(this.myForm.value);
}
}
接下来,在需要提交部分表单的组件中,使用FormControl来创建一个新的表单组。
partial-form.component.html:
partial-form.component.ts:
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-partial-form',
templateUrl: './partial-form.component.html',
styleUrls: ['./partial-form.component.css']
})
export class PartialFormComponent implements OnInit {
partialForm: FormGroup;
@Output() formSubmitted = new EventEmitter();
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.partialForm = this.fb.group({
firstName: '',
lastName: ''
});
}
onSubmit() {
this.formSubmitted.emit(this.partialForm.value);
}
}
在父组件中,使用EventEmitter来接收部分表单的提交事件。
app.component.html:
app.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
myForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.myForm = this.fb.group({
firstName: '',
lastName: '',
email: ''
});
}
onSubmit() {
console.log(this.myForm.value);
}
onPartialFormSubmitted(partialFormData: any) {
console.log(partialFormData);
}
}
当点击部分表单的Submit按钮时,会触发onPartialFormSubmitted方法,并将部分表单的数据作为参数传递给父组件。
希望以上代码能解决你的问题!