在Angular 5中,可以使用表单组来实现在不同组件中共享表单数据。以下是一种实现方法:
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
FormsModule,
ReactiveFormsModule
],
// other module configurations
})
export class AppModule { }
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-form',
template: `
<form [formGroup]="form">
<input formControlName="name" placeholder="Name">
<input formControlName="email" placeholder="Email">
</form>
`
})
export class FormComponent {
form: FormGroup;
constructor() {
this.form = new FormGroup({
name: new FormControl(''),
email: new FormControl('')
});
}
}
<app-form></app-form>
来引入。import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<h1>Parent Component</h1>
<app-form></app-form>
`
})
export class ParentComponent { }
import { Component } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<h2>Child Component</h2>
<app-form></app-form>
`
})
export class ChildComponent { }
这样,无论是在父组件还是子组件中使用<app-form></app-form>
,它们都将共享同一个表单组件实例,从而实现在不同组件中使用一个表单组。
关于Angular表单的更多信息,可以参考腾讯云的相关产品文档:Angular表单
领取专属 10元无门槛券
手把手带您无忧上云