如何使用Reactive表单在子组件中创建转发器控件

时间:2018-02-21 11:24:49

标签: html angular typescript

我在Angular项目中工作,我正在使用Reactive方法创建表单。我想在子组件中创建转发器控件。请找到以下代码。

MainComponent.html

<div [formGroup]="myForm">
   <input type="text" class="form-control" placeholder="Name"
                    formControlName="name" />
        <div formArrayName="measurements">
             <div *ngFor="let ctrl of myForm.get('measurements').controls; let i=index">
               <div [formGroupName]="i">
                  <measurement-edit [measurementForm]="myForm.controls.measurements.controls[i]">
                  </measurement-edit>
               </div>
           </div>
      </div>
      <div formArrayName="thresholds">
          <div *ngFor="let ctrl of myForm.get('thresholds').controls; let i = index">
              <div [formGroupName]="i">
                  <threshold-edit 
                     [thresholdForm]="myForm.controls.thresholds.controls[i]"
                     [valueType]="myForm.controls.valueType.value">
                  </threshold-edit>
              </div>
           </div>
      </div>
</div>

ThresholdEditComponent.html

<div [formGroup]="thresholdForm">
     <input type="checkbox"                     
                    [value]="isThresholdRequired"
                    formControlName="isThresholdRequired">
     <!-- Here I want to use repeater controls and these controls should be accessed from parent (main) commponent -->
     <div formArrayName="redThresholdItems">
          <div *ngFor="let itemRow of thresholdForm.get('redThresholdItems').controls; let j = index;">
              <div [formGroupName]="j">
                   <input type="text" 
                     class="form-control txt-thr-val-width"
                     formControlName="thresholdValue1" />
              </div>
          </div>
     </div>      
</div>

MainComponent.ts

ngOnInit(): void {    
   this.createForm();
}

createMetricForm(): void {
this.myForm = this.fb.group({
  name: ['', Validators.required],      
  easurements: this.fb.array([
    this.initMeasurements()
  ]),
  thresholds: this.fb.array([
    this.initThresholds()
  ])
});}

initMeasurements(): FormGroup {
return this.fb.group({
  isDerivedMetric: [false],
  baselineMetricId: [''],
  metricCalculation: [''],
  metricSelection: ['']
});}
initThresholds(): FormGroup {
return this.fb.group({
  isThresholdRequired: [false],      
  redThresholdItems: this.fb.array([
    this.initThresholdRatings()
  ])      
});}
initThresholdRatings(): FormGroup {
return this.fb.group({
  thresholdValue1Operator: ['-1'],
  thresholdValue1: [''],
  compoundOperator: ['-1'],
  thresholdValue2Operator: ['-1'],
  thresholdValue2: ['']
});}

请使用上面的代码帮助我在子组件中创建转发器控件。

0 个答案:

没有答案