如何解决我如何将相应的 FormGroup 传递给表单布局组件父?
我有一个表单布局,路由渲染在这个里面。使用 Angular Reactive Forms,我们必须在表单上定义 [formGroup] 指令。我有一个 Logup 和一个 Login(不同的表单结构),我在每个组件中构建了表单,但我不知道如何将它传递给父级。
这里是表单布局组件结构:
<form class="form-layout">
<router-outlet></router-outlet>
</form>
这是登录组件:
<div class="form-header">
<h4>Logup</h4>
<p>Complete to create your user</p>
</div>
<input type="text" class="form-control" placeholder="Name">
<input type="text" class="form-control" placeholder="Username">
<input type="email" class="form-control" placeholder="Email">
<div class="password-input">
<input [type]="showpwd ? 'text' : 'password'" class="form-control" placeholder="Password">
<i class="fas fa-eye" *ngIf="!showpwd" (click)="showpwd = true"></i>
<i class="fas fa-eye-slash" *ngIf="showpwd" (click)="showpwd = false"></i>
</div>
<button class="btn btn-primary">Submit</button>
<a routerLink="/login">
Already registered?
</a>
这是登录组件:
<div class="form-header">
<h4>Login</h4>
<p>Fill the form with your credentials</p>
</div>
<input type="text" class="form-control" placeholder="Username">
<div class="password-input">
<input [type]="showpwd ? 'text' : 'password'" class="form-control" placeholder="Password">
<i class="fas fa-eye" *ngIf="!showpwd" (click)="showpwd = true"></i>
<i class="fas fa-eye-slash" *ngIf="showpwd" (click)="showpwd = false"></i>
</div>
<button class="btn btn-primary">Submit</button>
<a routerLink="/logup">
Not registered yet?
</a>
最后是应用路由:
import { NgModule } from '@angular/core';
import { PreloadAllModules,RouterModule,Routes } from '@angular/router';
import { FormLayoutComponent } from './form-layout/form-layout.component';
const routes: Routes = [
{ path: '',component: FormLayoutComponent,children: [
{
path: 'logup',loadChildren: () => import('./pages/logup/logup.module').then(m => m.LogupModule),data: { animationType: 'logupAnimation' }
},{
path: 'login',loadChildren: () => import('./pages/login/login.module').then(m => m.LoginModule),data: { animationType: 'loginAnimation' }
},{ path: '',redirectTo: 'logup',pathMatch: 'full' }
]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes,{ preloadingStrategy: PreloadAllModules })],exports: [RouterModule]})
export class AppRoutingModule {};
解决方法
您可以在 formGroup
中声明 formGroup
,然后使用 DI 将其传递给每个孩子,而不是将 layoutComponent
from child 提供给 parent。
布局组件
@Component({
providers: [{
provide: 'FORM_GROUP_TOKEN',useFactory: (layoutComponent) => layoutComponent.formGroup,deps: [forwardRef(() => LayoutComponent )],}]
...
})
export LayoutComponent {
formGroup = new FormGroup(...)
...
}
然后每个子组件都可以@Inject('FORM_GROUP_TOKEN')
(NodeInjector
)并获得formGroup
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。