在将验证消息从组件映射到html时需要帮助

时间:2019-08-22 15:48:27

标签: angular angular-ui-router angular-material angular-directive

我对angular不熟悉,我在组件类中有验证错误,如您在下面的代码中所见,我在html中可以执行ngif,但是现在我想用html映射这些错误在组件类中, 我怎样才能做到这一点?

我尝试了此链接https://angular.io/guide/form-validation,但未指定应该怎么做。 感谢您的帮助。

import { Component } from '@angular/core';
import { Validators, FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'AngularProject';
  profileForm: FormGroup;
  submitted = false;

  constructor(private fb: FormBuilder) { }

  ngOnInit(): void {

    this.profileForm = this.fb.group({
      firstName: ['', [Validators.required, Validators.minLength(5)]],
      EmailMe: ['', [Validators.required, Validators.maxLength(9)]]
    });

    this.profileForm.get('firstName').valueChanges.subscribe(
      value => {
        console.log(value);
      }
    );
  }

  onSubmit(): void {
    this.onLoadDataClick();
    this.submitted = true;
    this.logKeyValuePairs(this.profileForm);
    if (this.profileForm.invalid) {
      return;
    }
    console.log(this.profileForm.value);
    alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.profileForm.value))
  }

  get f() {
    return this.profileForm.controls;
  }



  logKeyValuePairs(group: FormGroup): void {
    // loop through each key in the FormGroup
    Object.keys(group.controls).forEach((key: string) => {
      // Get a reference to the control using the FormGroup.get() method
      const abstractControl = group.get(key);
      // If the control is an instance of FormGroup i.e a nested FormGroup
      // then recursively call this same method (logKeyValuePairs) passing it
      // the FormGroup so we can get to the form controls in it
      if (abstractControl instanceof FormGroup) {
        this.logKeyValuePairs(abstractControl);
        // If the control is not a FormGroup then we know it's a FormControl
      } else {

        /////////////////////////////
        this.formErrors[key] = '';
      if (abstractControl && !abstractControl.valid) {
        // Get all the validation messages of the form control
        // that has failed the validation
        const messages = this.validationMessages[key];
        // Find which validation has failed. For example required,
        // minlength or maxlength. Store that error message in the
        // formErrors object. The UI will bind to this object to
        // display the validation errors
        for (const errorKey in abstractControl.errors) {
          if (errorKey) {
            this.formErrors[key] += messages[errorKey] + ' ';
          }
        }
      }
        /////////////////////////////


        console.log('Salil Key = ' + key + ' && Salil Value = ' + abstractControl.value);
      }
    });
  }


  // This object will hold the messages to be displayed to the user
// Notice, each key in this object has the same name as the
// corresponding form control
formErrors = {
  'fullName': '',
  'EmailMe': '',
};

// This object contains all the validation messages for this form
validationMessages = {
  'fullName': {
    'required': 'Full Name is required.',
    'minLength': 'Full Name must be greater than 2 characters.',
    'maxLength': 'Full Name must be less than 10 characters.'
  },
  'EmailMe': {
    'required': 'Email is required.',
    'minLength': 'Email must be greater than 2 characters.',
    'maxLength': 'Email must be less than 10 characters.'
  }
};




logValidationErrors(group: FormGroup): void {
  // Loop through each control key in the FormGroup
  Object.keys(group.controls).forEach((key: string) => {
    // Get the control. The control can be a nested form group
    const abstractControl = group.get(key);
    // If the control is nested form group, recursively call
    // this same method
    if (abstractControl instanceof FormGroup) {
      this.logValidationErrors(abstractControl);
      // If the control is a FormControl
    } else {
      // Clear the existing validation errors
      this.formErrors[key] = '';
      if (abstractControl && !abstractControl.valid) {
        // Get all the validation messages of the form control
        // that has failed the validation
        const messages = this.validationMessages[key];
        // Find which validation has failed. For example required,
        // minlength or maxlength. Store that error message in the


        // formErrors object. The UI will bind to this object to
        // display the validation errors
        for (const errorKey in abstractControl.errors) {
          if (errorKey) {
            this.formErrors[key] += messages[errorKey] + ' ';
          }
        }
      }
    }
  });
}


onLoadDataClick(): void {
  alert('hi hi');
  this.logValidationErrors(this.profileForm);
  console.log(this.formErrors);
}
}

<form 
  class="form-horizontal" 
  [formGroup]="profileForm" 
  (ngSubmit)="onSubmit()">
  <div class="panel panel-primary">
    <div class="panel-heading">
      <h3 class="panel-title">C3</h3>
    </div>
    <div class="panel-body">
      <div class="form-group">
        <label 
          class="col-sm-2 control-label" 
          for="fullName">
          Full Name
        </label>
        <div class="col-sm-8">
          <input 
            id="fullName" 
            type="text" 
            class="form-control" 
            formControlName="firstName">
          <div 
            *ngIf="profileForm.controls.firstName.touched && profileForm.controls.firstName.invalid"
            >
            First Name is required
          </div>
        </div>
      </div>
      <div class="form-group">
        <label class="col-sm-2 control-label" for="email">Email</label>
        <div class="col-sm-8">
          <input id="email" type="text" class="form-control" formControlName="EmailMe">
          <div 
            *ngIf="profileForm.controls.EmailMe.touched && profileForm.controls.EmailMe.invalid"
            >
            Email is required
          </div>
        </div>
      </div>
    </div>
    <div class="panel-footer">
      <button class="btn btn-primary" type="submit" [disabled]="profileForm.invalid">Save</button>
      <button class="btn btn-primary" type="submit" [disabled]="profileForm.invalid" (click)="onLoadDataClick()">Check Validation</button>
    </div>

  </div>
</form>

0 个答案:

没有答案