繁体   English   中英

我如何将相应的 FormGroup 传递给表单布局组件(父级)?

[英]How could i pass the respective FormGroup to form layout component (parent)?

我有一个表单布局,路由渲染在这个里面。 使用 Angular Reactive Forms,我们必须在表单上定义 [formGroup] 指令。 我有一个登录和登录(不同的表单结构),我在每个组件中构建表单,但我不知道如何将它传递给父级。

下面是表单布局组件结构:

<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 {};

您可以在layoutComponent中声明formGroup ,然后使用 DI 将其传递给每个孩子,而不是将formGroup从 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM