在FormArray反应性表单上实现表搜索

时间:2018-07-23 10:44:32

标签: angular typescript

我试图在我的Angular项目中的Reactive表单中实现表搜索功能。

我在实现过滤器管道时遇到一个问题,在该管道中需要一个FormArray,我想返回与条件匹配的过滤后的行。在强制转换FormArray时遇到问题。


HTML:

<input type="text" placeholder="Search Question" [(ngModel)]="QuestionToSearch" class="inputStyle" />

 <form [formGroup]="qnaTableForm" *ngIf="qnaTableForm">
        <table formArrayName="qnaTableDetailFormArray" class="table table-bordered table-hover">
          <thead>
            <tr>
              <th>#</th>
              <th>Question</th>
              <th>Answer</th>
              <th>Area</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
           <tr *ngFor="let item of formData.controls | searchQuestion : QuestionToSearch; let i=index" [formGroup]="item">
              <td width="1%">
                {{ i + 1 }}
              </td>
              <td width="30%">
                <textarea type='text' formControlName="question" placeholder="Enter Question" class="inputStyle" rows="5">
                </textarea>
              </td>
              <td width="60%">
                <textarea formControlName="answer" placeholder="Enter Answer" class="inputStyle" cols="40" rows="5">
                </textarea>
              </td>
              <td width="30%">
                <textarea type='text' formControlName="area" placeholder="Enter Area" class="inputStyle" rows="5">
                </textarea>
              </td>
              <td width="1%">
                <img src="assets/Images/ico_delete.png" title="Clicking on this will remove the Question-Answer pair from the database and is a permanent action." (click)="RemoveRows(i)" />
              </td>
            </tr>
          </tbody>

        </table>
      </form>

组件:

"use strict";

import { Component, OnInit, ElementRef } from '@angular/core';
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable } from 'rxjs/Observable';
import { FormGroup, FormBuilder, FormControl, Validators, FormArray, Form } from '@angular/forms';

@Component( {
  selector: 'app-mtqna',
  templateUrl: './mtqna.component.html',
  styleUrls: ['./mtqna.component.css']
} )
export class MtQnaComponent implements OnInit
{
  qnaModelList = [];
  QnaModelName: string;
  canNavigateAway: boolean = true;
  qnaTableForm: FormGroup;
  areChangesSavedIntoTheDatabase: boolean = true;
  QnaDataList: QnaMaker[] = new Array<QnaMaker>();
  isDefaultDropDownValue: boolean;
  QuestionToSearch: string;

  constructor( private httpClient: HttpClient, private fb: FormBuilder)
  {
  }

  //Property to get QnaTable Form data
  get formData(): FormArray
  {
    return <FormArray>this.qnaTableForm.get( 'qnaTableDetailFormArray' );
  }

  ngOnInit()
  {
    this.qnaTableForm = this.fb.group( {
      qnaTableDetailFormArray: this.fb.array( [this.InitializeFormArray()] )
    } )

    this.GetModels()
      .subscribe( data =>
      {
        if ( data )
          this.qnaModelList = data;
      },
        error =>
        {
          let errorMessage = error.content.value.message;
        });
    }

  GetModels(): Observable<any[]>
  {
    let url = `${sessionStorage.ServiceAddress}api/QNA/GetQnaModels?DomainName=${this.sharedService.SelectedBotName}&TenantName=${sessionStorage.TenantName}&UserName=${sessionStorage.UserName}`;

    return this.httpClient
      .get<any[]>( url );
  }

  GetQAPairsFromDatabaseByModel(): Observable<any[]>
  {
    let url = `${sessionStorage.ServiceAddress}api/QNA/GetPairsByModelName?DomainName=${this.sharedService.SelectedBotName}&TenantName=${sessionStorage.TenantName}&UserName=${sessionStorage.UserName}&ModelName=${this.QnaModelName}`;

    return this.httpClient
      .get<any[]>( url );
  }

  //Qna Model Change logic
  OnQnaModelChange( currentQnaModel: string ): void
  {
    this.QnaModelName = currentQnaModel || "";
    this.GetQAPairsFromDatabaseByModel()
      .subscribe( ( data: Array<QnaMaker> ) =>
      {
        if ( data )
          this.QnaDataList = data;

        //Display at least 1 Question-Answer pair if no data is present in the database
        if ( this.QnaDataList.length == 0 )
        {
          this.areChangesSavedIntoTheDatabase = false;
          this.qnaTableForm = this.fb.group( {
            qnaTableDetailFormArray: this.fb.array( [this.InitializeFormArray()] )
          } );
        }

        //Map response back to FormGroup[]
        if ( this.QnaDataList || this.QnaDataList.length >= 1 )
        {
          // We get our FormArray
          const controls = this.formData;
          controls.controls.splice( 0, controls.length );

          for ( let i = 0; i < this.QnaDataList.length; i++ )
          {
            // instantiate a new QA FormGroup;
            let qnaGroup: FormGroup = this.InitializeFormArray();

            qnaGroup.controls["question"].setValue( this.QnaDataList[i].Question );
            qnaGroup.controls["answer"].setValue( this.QnaDataList[i].Answer );
            qnaGroup.controls["area"].setValue( this.QnaDataList[i].Area );

            controls.controls.push( qnaGroup );
          }
        }
      },
        error =>
        {
          let errorMessage = error.content.value.message;
        });
  }

  // make a form for each row
  InitializeFormArray(): FormGroup
  {
    return this.fb.group( {
      question: [null, Validators.compose( [Validators.required, Validators.minLength( 2 )] )],
      answer: [null, Validators.compose( [Validators.required, Validators.minLength( 2 )] )],
      area: [null, Validators.compose( [Validators.required, Validators.minLength( 2 )] )]
    } );
  }

  //Add QA Pairs logic
  AddRow()
  {
    // This function instantiates a FormGroup and pushes it to our FormArray

    // We get our FormArray
    const control = <FormArray>this.qnaTableForm.controls['qnaTableDetailFormArray'];

    // instantiate a new day FormGroup;
    let qnaGroup: FormGroup = this.InitializeFormArray();

    // Add it to our formArray
    control.push( qnaGroup );

  }
}

管道:

import { Pipe, PipeTransform } from '@angular/core';
import { FormArray, FormGroup, FormControl, AbstractControl, Form } from '../../../../node_modules/@angular/forms';

@Pipe({
  name: 'searchQuestion'
})
export class SearchQuestionPipe implements PipeTransform {

  transform( FormControlArray: FormArray, searchQuestion: string )
  {
    if ( !searchQuestion || typeof ( searchQuestion ) === "undefined" || searchQuestion === "" || searchQuestion === null )
    {
      let forms = <Array<FormControl>>FormControlArray.controls; //Getting error here
      return forms;
    }

    //Getting error, as undefined and filter does not exist on FormControl[]    
    return (<Array<FormControl>>FormControlArray.controls).filter( x => x.value["question"].indexOf( searchQuestion ) != -1 ); 
  }
}

我认为我正确地输入了值,但是看不到更改。

0 个答案:

没有答案