devlev1980
7/10/2018 - 1:15 PM

Form Clarity

 formGroup: FormGroup; /*not in contructor*/
saveGroup() {
    this.errorMessage = '';
    this.groupService[this.isNew ? 'addGroup' : 'updateGroup'](this.group).subscribe(() => {
      return this.dialogRef.close(this.group);
    }, (err: HttpErrorResponse) => {
      if (err.error && err.error.Message) {
        if (err.error.ModelState) {
          for (let param in err.error.ModelState) {
            if (err.error.ModelState[param] instanceof Array) {
              let p = param.substr(param.lastIndexOf('.') + 1);
              if (this.myForm.controls[p]) {
                this.myForm.controls[p].setErrors({
                  serverErrors: (err.error.ModelState[param] || []).join('\n')
                });
              }
            }
          }
        }
        this.errorMessage = err.error.ExceptionMessage || err.error.Message;
      } else {
        this.errorMessage = 'Something went wrong';
      }
    });
  this.formGroup = new FormGroup({
      groupName: new FormControl(this.group.Name, Validators.required)
    });   /* in constructor*/
 get groupName(): AbstractControl | any {
    return this.formGroup.get('groupName');
  }

    <div class="clr-form-control clr-row">
      <label for="groupName" class="clr-control-label clr-col-xs-12 clr-col-sm-4">
        <div>{{ 'GROUP_NAME' | translate }}</div>
      </label>
      <div class="clr-control-container clr-col-xs-12 clr-col-sm-8" [class.clr-error]="groupName.dirty && groupName.errors">
        <input clrInput type="text" formControlName="groupName" id="groupName" name="groupName" required>
        <ng-container *ngIf="groupName.errors">
          <span class="clr-subtext" *ngIf="groupName.errors.required">{{ 'FORM_INPUT_REQUIRED' | translate }}</span>
          <span class="clr-subtext" *ngIf="groupName.errors.serverErrors">{{ groupName.errors['serverErrors'] }}</span>
        </ng-container>
      </div>
    </div>