2

嗨,我是 Angular 的新手,在我的表单中,我有三个字段Nameemail
radio 部分,我的要求是

-->当我选择名称单选按钮时,名称输入字段是必需的

-->当我选择电子邮件单选按钮时,电子邮件输入字段是必需的

我尽力了我的水平但没有结果我该怎么做这个要求有人可以帮助我吗

.html:

<form class="example-form" [formGroup]="emailForm">

    <!-- Name -->
    <mat-form-field class="example-full-width">
        <input matInput placeholder="Name" formControlName="name"
           [errorStateMatcher]="matcher" [(ngModel)]="name" [required]="radioModel=='1'">
             <mat-hint>Errors appear instantly!</mat-hint>
             <mat-error *ngIf="emailForm.get('name').hasError('required')">
               Name is <strong>required</strong>
             </mat-error>
  </mat-form-field>

  <!-- Email -->
  <mat-form-field class="example-full-width">
    <input matInput placeholder="Email" formControlName="email"
           [errorStateMatcher]="matcher" [(ngModel)]="email" [required]="radioModel=='2'">
    <mat-hint>Errors appear instantly!</mat-hint>
    <mat-error *ngIf="emailForm.get('email').hasError && !emailForm.get('email').hasError('required')">
      Please enter a valid email address
    </mat-error>
    <mat-error *ngIf="emailForm.get('email').hasError('required')">
      Email is <strong>required</strong>
    </mat-error>
  </mat-form-field>


<!-- Radio Button -->
<div class="radion-button">
  <mat-radio-group formControlName="radioGroup" [(ngModel)]="radioModel">
  <mat-radio-button value="1">Name</mat-radio-button>
  <mat-radio-button value="2">Email</mat-radio-button>
  <mat-error *ngIf="emailForm.get('radioGroup').hasError('required') && emailForm.get('radioGroup').touched">
               Selection is <strong>required</strong>
             </mat-error>
</mat-radio-group>
</div>
</form>

.ts:

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroupDirective, NgForm, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';

/** Error when invalid control is dirty, touched, or submitted. */
export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const isSubmitted = form && form.submitted;
    return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
  }
}

/** @title Input with a custom ErrorStateMatcher */
@Component({
  selector: 'input-error-state-matcher-example',
  templateUrl: './input-error-state-matcher-example.html',
  styleUrls: ['./input-error-state-matcher-example.css'],
})
export class InputErrorStateMatcherExample {
  emailForm: FormGroup;
  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {

    //Form Group
    this.emailForm = new FormGroup({
      email:new FormControl('', [Validators.required,Validators.email]),
      name:new FormControl('', [Validators.required]),
      radioGroup:new FormControl('',[Validators.required])
    });
  }
  matcher = new MyErrorStateMatcher();
}

我的代码----> https://stackblitz.com/edit/angular-2m1vdq-yfxnps

4

3 回答 3

4

如果Validators.required从 TS 文件中删除,它应该可以工作

this.emailForm = new FormGroup({
  email:new FormControl('', [Validators.email]),
  name:new FormControl('', []),
  radioGroup:new FormControl('',[Validators.required])
});

这是你的 StackBlitz 的一个分支

于 2018-11-01T09:26:39.277 回答
0

你可以使用NPM包。它简单易用,适用于反应式和模板驱动的表单。

代码片段:

HTML

<form [formGroup]="demoForm">
    <div>
         <label for="name">Name</label>
         <input type="text" formControlName="name" name="name" placeholder="Name validator">
         <tn-form-error [control]="demoForm.controls.name" [field]="'Name'"></tn-form-error>
    </div>
</form>

零件

<p>
 this.demoForm = new FormGroup({
      name: new FormControl(''[Validators.required])
 });

stackblitz

于 2021-05-31T17:53:37.233 回答
0

您可以根据条件使用 setValidators 向 FormControls 动态添加验证。

this.emailForm.get('radioGroup').valueChanges.subscribe(value=>{
      if(value === '1'){
        this.emailForm.get('name').setValidators(Validators.required);
        this.emailForm.get('name').updateValueAndValidity();
        alert('name is required');
      }else if(value === '2'){
        this.emailForm.get('email').setValidators(Validators.required);
        this.emailForm.get('name').updateValueAndValidity();
        alert('email is required');
      }
    });

https://stackblitz.com/edit/angular-2m1vdq-m5gnzz

于 2018-11-01T09:30:05.653 回答