Validate the input text user-entry inside table in angular 5

Viewed 319

html file

            <mat-table #table [dataSource]="CMDataSource">
              <ng-container matColumnDef="mQues">
                <mat-header-cell *matHeaderCellDef> Ticket Volume </mat-header-cell>
                <mat-cell *matCellDef="let element"> <label> {{element.mQues}} </label> </mat-cell>
              </ng-container>

              <ng-container matColumnDef="metricUnit">
                <mat-header-cell *matHeaderCellDef></mat-header-cell>
                <mat-cell *matCellDef="let element">
                  <mat-form-field>
                    <input type="number" matInput (change)="userMCState(element.mQuesId, $event.target.value)">
                  </mat-form-field>
                </mat-cell>
              </ng-container>
              <mat-header-row *matHeaderRowDef="displayedColumnsHeaderName"></mat-header-row>
              <mat-row *matRowDef="let row; columns: displayedColumnsHeaderName;">
              </mat-row>
            </mat-table>

          <button mat-raised-button (click)='submitMA()'> SUBMIT </button>

component file

const CM_DATA: MetricsAssess[] = [
  { mQuesId: 1, mQues: 'English', metricUnit: 'hour' },
  { mQuesId: 2, mQues: 'French', metricUnit: 'hour' },
  { mQuesId: 3, mQues: 'Spanish', metricUnit: 'hour' },
  { mQuesId: 4, mQues: 'German', metricUnit: 'hour' }
];
  CMDataSource = new MatTableDataSource(CM_DATA);

  userMCState(questionNum, statusValue): void {
    this.mArray.push({ "quesNum": questionNum, "userAns": statusValue});
  }

   submitMA(): void {
**//VALIDATE THE USER INPUT & if the ENTRY is BLANK, request the user to make entry**
    let pMDataJSON = {
      mAssessJSONArray: this.mArray
    };
  }

Here, is a set of questions displayed from table & also input text boxes. Need to validate the User entry is NUMBER and also, if no entry is made then, request dialog box to make entry. Kindly help me.

1 Answers

Please fallow thiese below steps.

  • remove change event because it triggers in every value changes. try and use with ngModel

<input type="number" matInput [(ngModel)]= "element.statusValue">

  • do your validation in submitMA() by using loop, like below way

 submitMA(): void {
    let isError=false;
    for(const obj of this.mArray)
    {
    if(!obj.statusValue || !Number.isInteger(obj.statusValue))
    {
    isError=true;
    alert(some error occurred)
    break;
    }
    
    if(isError)
    {
    return false
    }
    }
   // .. possitive scenario codes 
    }

Note: your model class should have statusValue property.

Related