Сделайте поле формы обязательным на основе другого значения поля в угловых 5 - PullRequest
0 голосов
/ 01 июня 2018

У меня есть следующая форма.Я хочу сделать тип графика обязательным.Однако значения осей X и Y должны быть обязательными, только если график представляет собой гистограмму или линейный график, а не круговую или кольцевую диаграмму.Согласно моему коду, значения осей X и Y являются обязательными.Пожалуйста, помогите.

html

    <form [formGroup]="clientForm" (ngSubmit)="clientForm.valid && changeGraph()" #formLogin="ngForm">

              <div class="form-group">
            <label> Graph Type </label>
            <select class="form-control" formControlName="type">
              <option disabled [ngValue]="null"> Select Option </option>
              <option *ngFor='let t of types' [ngValue]="t"> {{t}} </option>
            </select>
            <div class="form-err" *ngIf="(clientForm.controls['type'].hasError('required') && clientForm.controls['type'].touched) || (clientForm.controls['type'].hasError('required') && formLogin.submitted)"> Please enter Graph Type </div>
              </div>

              <div class="form-group">
            <label> X-Axis </label>
            <select class="form-control" formControlName="xAxis">
              <option disabled [ngValue]="null"> Select Option </option>
              <option *ngFor='let dim of dimensions?.data' [ngValue]="dim"> {{dim}} </option>
            </select>
            <div class="form-err" *ngIf="(clientForm.controls['xAxis'].hasError('required') && clientForm.controls['xAxis'].touched) || (clientForm.controls['xAxis'].hasError('required') && formLogin.submitted)"> Please enter Dimension </div>
              </div>

              <div class="form-group">
            <label> Y-Axis </label>
            <select class="form-control" formControlName="yAxis">
              <option disabled [ngValue]="null"> Select Option </option>
              <option *ngFor='let dim of dimensions?.data' [ngValue]="dim"> {{dim}} </option>
            </select>
            <div class="form-err" *ngIf="(clientForm.controls['yAxis'].hasError('required') && clientForm.controls['yAxis'].touched) || (clientForm.controls['yAxis'].hasError('required') && formLogin.submitted)"> Please enter Measure </div>
              </div>

              <button class="client-side-window-btn" type="submit">
            Save
              </button>

     </form>

ts

    import { Component, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
    import { FormGroup, FormBuilder, Validators, FormControl, FormsModule } from '@angular/forms';

    @Component({
      selector: 'app-client',
      templateUrl: './client.component.html',
      styleUrls: ['./client.component.css']
    })
    export class ClientComponent implements OnInit {

      //Form params
      clientForm: FormGroup;
      type:FormControl;
      xAxis:FormControl;
      yAxis:FormControl;


      //dropdown arrays
      public dimensions:string[]= ['Plant','Year','Month'];

      public types: string[]= ['bar','line','pie','doughnut'];

        constructor(
          private form:FormBuilder,
          private forms:FormsModule) {
     }

        ngOnInit() {
          this.clientForm = this.form.group({
           'type': [null, Validators.required],
           'xAxis': [null, Validators.required],
           'yAxis': [null, Validators.required],
         });
      }
    }

1 Ответ

0 голосов
/ 01 июня 2018

С помощью (change)="callback()" вы можете запустить функцию.Затем с помощью formControl.setValidators() вы можете установить валидаторы.

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

вам также понадобится formControl.updateValueAndValidity() для фактического запуска валидаций.

StackBlits Here

Обратите внимание, что вы не можете читать текущие валидаторы (на самом деле это возможно, но довольно сложно), но только перезаписать их.

html

            <select (change)="updateAxisFields()" class="form-control" formControlName="type">
              <option disabled [ngValue]="null"> Select Option </option>
              <option *ngFor='let t of types' [ngValue]="t"> {{t}} </option>
            </select>

ts

    @Component({
      selector: 'app-client',
      templateUrl: './client.component.html',
      styleUrls: ['./client.component.css']
    })
    export class ClientComponent implements OnInit {

      //Form params
      optional: string[] = ['pie', 'doughnut'];
      clientForm: FormGroup;
      type:FormControl;
      xAxis:FormControl;
      yAxis:FormControl;


      //dropdown arrays
      public dimensions:string[]= ['Plant','Year','Month'];

      public types: string[]= ['bar','line','pie','doughnut'];

        constructor(
          private form:FormBuilder,
          private forms:FormsModule) {
     }

        ngOnInit() {
          this.clientForm = this.form.group({
           'type': [null, Validators.required],
           'xAxis': [null, Validators.required],
           'yAxis': [null, Validators.required],
         });
      }

   updateAxisFields(): void {
        console.info("updateAxis");
        const type = this.clientForm.controls.type.value;

        const xAxis = this.clientForm.controls.xAxis;
        const yAxis = this.clientForm.controls.yAxis;
        const newValidators = [];
        this.axisRequired = this.optional.indexOf(type) > -1
        if (this.axisRequired) {
          newValidators.push(Validators.required);
        }
        xAxis.setValidators(newValidators);
        xAxis.updateValueAndValidity();
        yAxis.setValidators(newValidators);
        yAxis.updateValueAndValidity();
     }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...