Сравните значения 2 полей ввода для проверки формы в Angular 7 через шаблон - PullRequest
1 голос
/ 29 сентября 2019

Я в первые недели перехода на Angular 7, я выполнял базовые формы в своем проекте, используя базовые проверки на основе шаблонов, но теперь мне нужно проверить форму на основе того, что значение одного поля должно бытьвыше, чем другие

Я пытался использовать сами значения в контроллере компонента, но хотя я могу подтвердить, что значения действительны или нет, я не могу показать пользователю, в чем проблемаесть, используя этот код

if (issueThresholdForm.value.lowScore > issueThresholdForm.value.highScore) {
  // Show user error
  // This is the messing part, I guess
}

Вот шаблон, который я использую

<div *ngIf="_issueCategory">
  <form (submit)="submitIssueThreshold(issueThresholdForm)" #issueThresholdForm="ngForm">
    <mat-form-field class="half-width" floatLabel="always">
      <mat-label [translate]="'issueThreshold.modals.highScore'"></mat-label>
      <input name="highScore" type="number" matInput placeholder="0" [(ngModel)]="_issueCategory.highScore"
        required #highScore="ngModel">
    </mat-form-field>
    <mat-form-field class="half-width" floatLabel="always">
      <mat-label [translate]="'issueThreshold.modals.lowScore'"></mat-label>
      <input name="lowScore" type="number" matInput placeholder="0" [(ngModel)]="_issueCategory.lowScore"
        required #lowScore="ngModel">
    </mat-form-field>
    <mat-form-field class="full-width" floatLabel="always">
      <mat-label [translate]="'issueThreshold.modals.description'"></mat-label>
      <textarea name="description" matInput [(ngModel)]="_issueCategory.thresholdDescription">
            </textarea>
    </mat-form-field>
    <div class="modal-footer">
      <button type="button" class="btn btn-secondary" data-dismiss="modal" [translate]="'modal-confirm.cancel'"></button>
      <button type="submit" class="btn btn-primary primary" [disabled]="issueThresholdForm.invalid || issueThresholdForm.pristine" [translate]="'modal-confirm.submit'"></button>
    </div>
  </form>
</div>

Ответы [ 3 ]

3 голосов
/ 29 сентября 2019

Я настоятельно рекомендую Реактивные формы, но если вы хотите сделать это, вы можете:

поставить следующее p tag под входом lowScore:

<p class="text-danger" [hidden]="(lowerScore.value > higerScore.value ? false: true) || (lowScore.pristine && !issueThresholdForm.submitted)">
                    The lower scrore can not be greater than higer score
</p>
1 голос
/ 29 сентября 2019

РЕДАКТИРОВАТЬ:

Отредактировано с тем же решением реактивный путь.Поэтому создайте группу форм и добавьте собственный валидатор, присоединенный к группе форм:

_issueCategory = { lowScore: 1, highScore: 2 };

issueThresholdForm: FormGroup;

constructor(private fb: FormBuilder) {
  this.issueThresholdForm = this.fb.group({
    highScore: [this._issueCategory.highScore, [Validators.required]],
    lowScore: [this._issueCategory.lowScore, [Validators.required]]
  }, { validators: validateScore })
}

Функция валидатора:

export function validateScore(
  control: AbstractControl
): ValidationErrors | null {
  if (control && control.get("highScore") && control.get("lowScore")) {
    const highscore = control.get("highScore").value;
    const lowscore = control.get("lowScore").value;  
    return (lowscore > highscore) ? { scoreError: true } : null
  }
  return null;
}

Затем вы можете удалить ngModel (важно!), Так как они не должны бытьсмешивается с реактивными формами.Также вы можете удалить все проверки, такие как required для формы, поэтому в конце вход может выглядеть просто:

<input type="number" matInput placeholder="0" formControlName="lowScore">

STACKBLITZ


ОРИГИНАЛ:

Я сильно, сильно предлагаю Реактивные формы , они могут чувствовать себя сбивающими с толкусначала, но оно того стоит.Вы лучше контролируете форму, и, как уже упоминалось в комментарии Нитина Кумара Билия, модульное тестирование проще.

При этом ....

Вот решение с использованием шаблонно-управляемой формы, поскольку это то, что вы в настоящее время используете.

Вы можете создать директиву, которую вы прикрепляете к тегу формы, и внутри этой директивы есть валидатор для сравнения значений рекордов и низших баллов и добавления ошибки к форме или возврата null (чтосчитается действительным в формах).Таким образом, валидатор будет выглядеть так:

import { Directive } from "@angular/core";
import {
  AbstractControl,
  NG_VALIDATORS,
  Validator,
  ValidationErrors
} from "@angular/forms";

@Directive({
  selector: "[scoreValidation]",
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: ScoreValidatorDirective,
      multi: true
    }
  ]
})
export class ScoreValidatorDirective implements Validator {
  constructor() {}

  // here control is the formgroup
  validate(control: AbstractControl): ValidationErrors | null {
    if (control && control.get("highScore") && control.get("lowScore")) {

      // the form controls and their value
      const highscore = control.get("highScore").value;
      const lowscore = control.get("lowScore").value;

      // not valid, return an error
      if (lowscore > highscore) {
        return { scoreError: true };
      }
      // valid
      return null;
    }
    // form controls do not exist yet, return null
    return null;
  }
}

Добавьте директиву к массиву объявлений в вашем приложении и используйте ее, просто прикрепив эту директиву к тегу формы:

<form .... scoreValidation>

и ошибка может быть показана с помощью *ngIf="issueThresholdForm.hasError('scoreError')

STACKBLITZ

0 голосов
/ 29 сентября 2019

Вы можете использовать Custom Validations в Reactive Forms следующим образом.

HTML

<div>
  <form [formGroup]="myForm">

    <label>Low Score: </label>
    <input formControlName="lowScore" type="number">
    <br/><br/>
    <label>High Score: </label>
    <input formControlName="highScore" type="number">

    <div>
      <span style="color: red" *ngIf="myForm.get('highScore').touched && myForm.get('highScore').hasError('higherThan')">High score should be higher than lower score.</span>
    </div>

  </form>
</div>

TS

export class AppComponent  {
  myForm: FormGroup;

  constructor() {

    this.myForm = new FormGroup({
      highScore: new FormControl(0, [this.lowerThan('lowScore')]),
      lowScore: new FormControl(0, null)
    });
  }
  lowerThan(field_name): ValidatorFn {

    return (control: AbstractControl): { [key: string]: any } => {

      const input = control.value;

      const isLower = control.root.value[field_name] >= input;

      return isLower ? {'lowerThan': {isLower}}: null;
    };
  }
}

Найти рабочий StackBlitz Здесь .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...