嗨,我是 Angular 的新手,在我的表单中,我有三个字段Name、email
和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();
}