【问题标题】:How to validate the reactive forms for dynamic input in angular如何验证角度动态输入的反应形式
【发布时间】:2020-03-31 10:51:18
【问题描述】:

我创建了一个带有角材料的反应形式。我有一个选择下拉菜单,所以基于下拉选择。输入字段将更改。所以现在使用下面的代码。如果我只是提交它,它会将数组发送到我的后端。如果我启用按钮的禁用选项,如果我的表单有 8 个输入,则无法提交。但是当我选择一个选项时,它将只有 6 个字段。那么如何进行验证以限制用户提交空表单。

下面是我的 HTML 代码

<div class = "tp-container">
      <form [formGroup]="myForm" (ngSubmit)="submitForm()">
        <!-- Name -->
        <mat-form-field class="example-full-width" >
          <input matInput placeholder="Name" formControlName="name">
          <!-- error -->
          <mat-error *ngIf="errorHandling('name', 'required')">
            You must provide a <strong> Name</strong>
          </mat-error>
        </mat-form-field>

        <!-- Email -->
        <mat-form-field class="example-full-width">
          <input matInput placeholder="Email" formControlName="email">
          <!-- error -->
          <mat-error *ngIf="errorHandling('email', 'required')">
            You must provide a <strong>email</strong>
          </mat-error>
        </mat-form-field>

            <!-- Class -->
            <mat-form-field>
                <mat-label>Item</mat-label>
                <mat-select [(value)]="selected" formControlName="Items">
                  <mat-option [value]="item" *ngFor="let item of Items">{{item}}
                  </mat-option>
                </mat-select>
              </mat-form-field>

     <!-- Eng Name -->
     <mat-form-field class="example-full-width">
        <input matInput placeholder="Name" formControlName="engname">
        <!-- error -->
        <mat-error *ngIf="errorHandling('engname', 'required')">
          You must provide a <strong>Name</strong>
        </mat-error>
      </mat-form-field>

       <!-- JP Name -->
       <div *ngIf="myForm.get('Items').value == 'Mobile">
       <mat-form-field class="example-full-width" >
        <input matInput placeholder="JP Name" formControlName="jpname">
        <!-- error -->
        <mat-error *ngIf="errorHandling('jpname', 'required')">
          You must provide a <strong> Japanese Name</strong>
        </mat-error>
      </mat-form-field></div>

      <!-- LAN ID Name -->
      <div *ngIf="myForm.get('Items').value == 'Software'">
        <mat-form-field class="example-full-width" >
         <input matInput placeholder="LAN ID" formControlName="lan">
         <!-- error -->
         <mat-error *ngIf="errorHandling('lan', 'required')">
           Please provide your <strong> LAN ID</strong>
         </mat-error>
       </mat-form-field></div>

                    <!-- Application Name -->
      <div *ngIf="myForm.get('Items').value == 'Network'">
        <mat-form-field class="example-full-width" >
         <input matInput placeholder="Application Name" formControlName="app">
         <!-- error -->
         <mat-error *ngIf="errorHandling('app', 'required')">
           Please provide the <strong>Application Name</strong>
         </mat-error>
       </mat-form-field></div>

        <!-- Submit -->
        <div class="button-wrapper">
          <button type="submit" color=#C93C6A class="btn-block" >Submit</button>
        </div>

      </form>
    </div>

下面是我的 ts 文件:

import { Component,OnInit, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { HttpClient } from '@angular/common/http';

export interface Subject {
  name: string;
}
@Component({
  selector: 'app-lan',
  templateUrl: './lan.component.html',
  styleUrls: ['./lan.component.css']
})
export class LanComponent implements OnInit {

  myForm: FormGroup;

  Items: any = ['Mobile', 'Software','Network','Others'];


  constructor(public fb: FormBuilder,private http: HttpClient,) {}

  public selected = '';
  ngOnInit(): void {
    this.reactiveForm()
  }

  /* Reactive form */
  reactiveForm() {
    this.myForm = this.fb.group({
      name: ['', [Validators.required]],
      email: ['', [Validators.required]],
      Items:[''],
      request: ['Urgent'],
      startdate: ['', [Validators.required]],
      subjects: [this.SubjectsArray],
      engname: ['', [Validators.required]],
      jpname: ['', [Validators.required]],
      lan:['', [Validators.required]],
      soft:['', [Validators.required]],
      server:['', [Validators.required]],
      remarks:['']

    })
  }

  submitForm() {
    var formData: any = new FormData();
    formData.append("name", this.myForm.get('name').value);
    formData.append("email", this.myForm.get('email').value);
    formData.append("Items", this.myForm.get('Items').value);
    formData.append("request", this.myForm.get('request').value);
    formData.append("startdate", this.myForm.get('startdate').value);
    formData.append("subjects", this.myForm.get('subjects').value);
    formData.append("engname", this.myForm.get('engname').value);
    formData.append("jpname", this.myForm.get('jpname').value);
    formData.append("lan", this.myForm.get('lan').value);
    formData.append("soft", this.myForm.get('soft').value);
    formData.append("version", this.myForm.get('version').value);
    formData.append("reason", this.myForm.get('reason').value);
    formData.append("app", this.myForm.get('app').value);
    formData.append("server", this.myForm.get('server').value);
     formData.append("remarks", this.myForm.get('remarks').value);
    formData.append("port", this.myForm.get('port').value);

    console.log(this.myForm)
    this.http.post('API url', this.myForm.value).subscribe(
      (response) => console.log(response),
      (error) => console.log(error))
    console.log("Form Submitted!");
    this.myForm.reset();
  }

}

【问题讨论】:

    标签: angular angular-material angular8 angular-reactive-forms


    【解决方案1】:

    您可以通过两种方式检查验证

     isAddedElement : boolean = false;
     changeForValue() {
        this.isAddedElement.valueChanges.subscribe(x => {
          this.isAddedElement = x;
          if (x) {
            this.myForm.addControl('ctrl1', new FormControl('', Validators.required));
            this.myForm.addControl('ctrl2', new FormControl('', Validators.required));
          } else {
            this.myForm.removeControl('ctrl1');
            this.myForm.removeControl('ctrl2');
          };
        });
      }
    

    HTML

                <div class="row" *ngIf="isAddedElement">
              <div class="col s12">
                <mat-form-field class="example-full-width">
                  <input matInput placeholder="ctrl1" required formControlName="ctrl1">
                  <mat-error *ngIf="myForm.get('ctrl1').hasError('required')">
                    ctrl1 is <strong>required</strong>
                  </mat-error>
                </mat-form-field>
              </div>
            </div>
    

    【讨论】:

    • 谢谢您的回答.. 让我这样说.. myform 共有 16 个字段.. 但所有 16 个字段在表单上都不可见.. 我的 ngif 条件很少.. 当我从下拉列表中选择网络,然后我可以在这种情况下看到 10 个输入字段,当我应用 2 个解决方案中的任何一个时它都不起作用.. 因为 myform 只有在所有 16 个字段都填满时才有效.. 我希望这能澄清
    • 可以动态添加这6个字段的valueChange事件。
    • 请告诉我该怎么做?有点新的角度
    • 我正在编辑答案检查它。如果它 ctrl 是 thair 则有效,否则将其删除。
    • 我有四个选项.. 选项 1 需要 12 个输入,选项 2 有 8 个选项 3 有 8 个,选项 4 有 10 个输入.. 在这种情况下,if 条件将基于布尔值创建新表单控件?
    猜你喜欢
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    相关资源
    最近更新 更多