表单内的多个子组件 - Angular 2

时间:2017-02-13 11:37:28

标签: angular angular2-forms angular2-directives

我正在处理大型表单,因此我计划将表单截断为多个子组件,这有助于轻松集成和维护。使用表单生成器我试图实现这一点。

mainform.html

           Select distinct
          `users`.`name` as user_name,
          `practices`.`name` as practice_name,
          `userlevels`.`name` as userlevel_name,
          `usertypes`.`name` as usertypes_name,              
          `users`.`active` as user_status,
          `users`.`email` as user_email              
           from `network_user`
           left join `users` on `network_user`.`user_id` = `users`.`id`
           left join `practice_user` on `users`.`id`=`practice_user`.`user_id`
           left join `practices` on `practice_user`.`practice_id`=`practices`.`id`
           left join `userlevels` on `users`.`level`=`userlevels`.`id`
           left join `usertypes` on `users`.`usertype_id`=`usertypes`.`id`
           where `network_user`.`network_id`= 9
           ;

mainform.ts

    <form novalidate (ngSubmit)="onSubmit(formDetail);" [formGroup]="formDetail">
      <label>
        <span>Name</span>
          <input
          type="text"
          placeholder="Enter emp name"
          formControlName="name">
      </label>
      <app-userinfo></app-userinfo> <!-- Child component 1 -->
      <app-useracc></app-useracc> <!-- Child component 2 -->
    </form>

CONSOLE.LOG

export class MainformComponent implements OnInit {
  formDetail: FormGroup;
  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
      this.formDetail= this.formBuilder.group({
        name:'',
      userinfo: this.formBuilder.group({
        userid: '',
        userph: ''
      }),
      useracc: this.formBuilder.group({
        useracc: '',
        usertransfer: ''
      })
    });
  }
  onSubmit(value:User){
    debugger;
  }
}

是否可以将表单组件嵌套为单独的子组件?

1 个答案:

答案 0 :(得分:12)

您需要使用Input()并将该子FormGroup传递给孩子。我在这里更改了一点,并将组名为useraccount而不是useracc,以将控件与组分开:

您父母的useraccount子组:

  ...
  useraccount: this.formBuilder.group({
    useracc: '',
  })
  ...

因此,父级中的相关子组件标记应如下所示:

<app-useracc [useraccount]="formDetail.controls.useraccount"></app-useracc>

然后在您的子组件中添加输入:

@Input() useraccount: FormGroup;

和模板看起来像这样:

<div [formGroup]="useraccount">
  <input formControlName="useracc">
</div>

工作sample