将子组件表单绑定到父组件表单

时间:2019-04-25 03:58:51

标签: angular angular6 angular5 angular7

我有两个组成部分:父母孩子。 我在相应的组件中为父级和子级创建了两个表单组

  

反应式模型

,我必须将子表单组绑定到父表单组。 有可能做。

注意: 我正在将父表单传递给子组件

1 个答案:

答案 0 :(得分:2)

您不必为此创建表格组。 您必须将父表单组传递给孩子。

在父组件中创建formgroup和formcontrol,并使用@input在子组件中传递fromcontrol和formgroup。

无论何时提交表单,您都将从子组件字段中获取值。

浏览以下代码  父组件

<form [formGroup]="operatorForm" #formElement>
    <div class="inner">
      <!-- <h6>Donation Collected</h6> Text only For Churches Panel -->
      <app-date-filter
        [fromDate]="fromDate"
        [toDate]="toDate"
        [dateForm]="operatorForm"
      ></app-date-filter>
      <div>
        <mat-form-field>
          <mat-select
            formControlName="status"
            (selectionChange)="filterChange($event)"
            placeholder="Filter Type"
          >
            <mat-option [value]="FILTER_TYPE.active"> Active </mat-option>
            <mat-option [value]="FILTER_TYPE.blocked"> Blocked </mat-option>
            <mat-option [value]="FILTER_TYPE.deleted"> Deleted </mat-option>
          </mat-select>
        </mat-form-field>
      </div>


    </div>
    <div class="btn-wrap filterBtns">
      <button
        mat-raised-button
        (click)="reset()"
        [disabled]="!operatorForm.dirty"
      >
        Reset
      </button>
      <button
        (click)="filter()"
        mat-raised-button
        color="primary"
        class="ml10 mat-filter-button"
        [disabled]="!operatorForm.dirty"
      >
        Filter
      </button>
    </div>
  </form>

parent.component.ts

this.operatorForm = this._fb.group({
  fromDate: ['', []],
  toDate: ['', []],
  status: [null, []]
});
get fromDate():FormControl{ 
 return this.operatorForm.controls['fromDate'] as FormControl 
} 
get toDate():FormControl{
 return this.operatorForm.controls['toDate'] as FormControl
}

子组件

    @Input() fromDate: FormControl;
  @Input() toDate: FormControl;

  @Input() dateForm: FormGroup;

    <div class="inner" [formGroup]="dateForm">
  <label for="">Added On</label>
  <div class="column">
    <mat-form-field>
      <input
        matInput
        readonly
        [matDatepicker]="frompicker"
        formControlName="fromDate"
        placeholder="From"
      />
      <mat-datepicker-toggle
        matSuffix
        [for]="frompicker"
      ></mat-datepicker-toggle>
      <mat-datepicker #frompicker></mat-datepicker>
    </mat-form-field>
  </div>
  <div class="column">
    <mat-form-field>
      <input
        matInput
        readonly
        [matDatepicker]="topicker"
        formControlName="toDate"
        placeholder="To"
      />
      <mat-datepicker-toggle matSuffix [for]="topicker"></mat-datepicker-toggle>
      <mat-datepicker #topicker></mat-datepicker>
    </mat-form-field>
  </div>
</div>