Javascript 如何显示<;span>;表单验证时角度模板中的元素?

Javascript 如何显示<;span>;表单验证时角度模板中的元素?,javascript,css,angular,typescript,reactive,Javascript,Css,Angular,Typescript,Reactive,所以我在做这个角度反应形式的项目,我有一个有趣的问题。 我的任务是显示验证中的错误,每个表单输入下面都有一个无效的范围。表单输入应在从中单击时进行验证,表单应在提交时进行验证。 我需要在outclick上呈现我的span元素,但同时,如果我从未在任何输入中输入任何内容并提交表单,则应呈现相同的span。 所以,要么我输入了一些无效的内容,表单用span告诉我,要么我点击提交按钮,表单显示每个无效输入的span。 我希望所有跨度都可以通过编程添加,但通过模板也可以。 我的逻辑是将所有“错误”(基本

所以我在做这个角度反应形式的项目,我有一个有趣的问题。 我的任务是显示验证中的错误,每个表单输入下面都有一个无效的范围。表单输入应在从中单击时进行验证,表单应在提交时进行验证。 我需要在outclick上呈现我的span元素,但同时,如果我从未在任何输入中输入任何内容并提交表单,则应呈现相同的span。 所以,要么我输入了一些无效的内容,表单用span告诉我,要么我点击提交按钮,表单显示每个无效输入的span。 我希望所有跨度都可以通过编程添加,但通过模板也可以。 我的逻辑是将所有“错误”(基本上是每个跨度的内容)保存到一个数组中,并将所有状态保存到一个数组中,然后通过循环和模板绑定来显示它们。 我既想不出我的想法的逻辑,也想不出一个更简单的解决方案。请帮帮我

我的模板:

<form class="form" [formGroup]="signUpForm" (ngSubmit)="onSubmit()">
    <div class="form__group form__group--name">
        <div class="form__control form__first-name">
            <input type="text" name="Fname" required formControlName="firstName" a-ngblur="onBlur(true)">
            <label>First Name</label>
        </div>
        <div class="form__control form__last-name">
            <input type="text" name="Lname" required formControlName="lastName">
            <label>Last Name</label>
        </div>
    </div>
    <div class="form__group form__group--id">
        <div class="form__control form__email">
            <input type="text" name="email" required formControlName="email">
            <label>Email ID</label>
        </div>
        <div class="form__control form__ID">
            <input type="text" name="ID" required formControlName="id">
            <label>Your User ID</label>
        </div>
    </div>
    <div class="form__group form__group--location form-group">
        <div class="form__control form__country">
            <span>Country</span>
            <select class="form-control" name="country" formControlName="country" (change)="onChange()" (click)="onOpen('country')">
                <option [value]="null" disabled>Choose your country</option>
                <option  *ngFor="let country of countries"  [value]="country.value">{{ country.value }}</option>
            </select>
        </div>
        <div class="form__control form__location">
            <div class="form__location--state" [ngSwitch]="this.signUpForm.get('country').value">
                <span>State</span>
                <select name="state" formControlName="state" *ngSwitchCase="'USA'">
                    <option [value]="null" disabled>Choose state</option>
                    <option *ngFor="let state of statesUSA"  [value]="state.value">{{ state.value }}</option>
                </select>
                <select name="state" formControlName="state" *ngSwitchCase="'India'">
                    <option [value]="null" disabled>Choose state</option>
                    <option *ngFor="let state of statesIndia"  [value]="state.value">{{ state.value }}</option>
                </select>
                <select name="state" formControlName="state" *ngSwitchCase="undefined">
                    <option [value]="null" disabled>Choose state</option>
                </select>
            </div>
            <div class="form__location--city" [ngSwitch]="this.signUpForm.get('state').value">  
                <span>City</span>
                <select name="city" formControlName="city" *ngSwitchCase="'New York'">
                    <option [value]="null" disabled>Choose city</option>
                    <option *ngFor="let city of citiesNY"  [value]="city.value">{{ city.value }}</option>
                </select>
                <select name="city" formControlName="city" *ngSwitchCase="'California'">
                    <option [value]="null" disabled>Choose city</option>
                    <option *ngFor="let city of citiesCali"  [value]="city.value">{{ city.value }}</option>
                </select>
                <select name="city" formControlName="city" *ngSwitchCase="'Andhra Pradesh'">
                    <option [value]="null" disabled>Choose city</option>
                    <option *ngFor="let city of citiesAndhra"  [value]="city.value">{{ city.value }}</option>
                </select>
                <select name="city" formControlName="city" *ngSwitchCase="'Goa'">
                    <option [value]="null" disabled>Choose city</option>
                    <option *ngFor="let city of citiesGoa"  [value]="city.value">{{ city.value }}</option>
                </select>
                <select name="city" formControlName="city" *ngSwitchCase="undefined">
                    <option [value]="null" disabled>Choose city</option>
                </select>
            </div>
        </div>
    </div>
    <div class="form__group form__control--data">
        <div class="form__control form__phone">
            <input type="text" name="phone" required formControlName="phone" #phoneInput
            [imask]="{mask: '+{38}(000)000-00-00'}" [unmask]="true">
            <label>Phone Number</label>
        </div>
        <div class="form__control form__code">
            <input type="text" name="code" class="ref-code" formControlName="code" style="text-transform: uppercase;">
            <label>Reference Code</label>
        </div>
    </div>
    <div class="form__group form__group--buttons">
        <a type="button" (click)="onReset()" class="form__group--buttons-reset">Reset All</a>
        <button type="submit" class="form__group--buttons-submit">Continue</button>
    </div>
</form>

名字
姓
电子邮件ID
您的用户ID
国家
选择你的国家
{{country.value}
陈述
选择州
{{state.value}}
选择州
{{state.value}}
选择州
城市
选择城市
{{city.value}
选择城市
{{city.value}
选择城市
{{city.value}
选择城市
{{city.value}
选择城市
电话号码
参考代码
全部重置
继续
我的TS:

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { FormGroup, FormControl, FormArray, Validators } from '@angular/forms';
import { storageService } from '../storage-service.component';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit {
  signUpForm: FormGroup;
  countries = [
    new FormControl('USA'),
    new FormControl('India')
  ];

  statesUSA = [new FormControl('New York'), new FormControl('California')];
  statesIndia = [new FormControl('Andhra Pradesh'), new FormControl('Goa')]

  citiesNY = [new FormControl('Albany'), new FormControl('New York City')];
  citiesCali = [new FormControl('Sacramento'), new FormControl('Los Angeles'), new FormControl('San Francisco')];
  citiesAndhra = [new FormControl('Visakhapatnam'), new FormControl('Amaravati')];
  citiesGoa = [new FormControl('Panaji'), new FormControl('Vasco da Gama')];

  @ViewChild('phoneInput', {static: false}) phoneInput: ElementRef;
  public mask:any = {
    mask: '+{38}(0__)000-00-00',
    lazy: false
  }

  invalidMessages = ['This field is required and has to contain 2-32 cyrillic characters!', 
  'This field is required and has to be a valid email address!',
  'This is a required field!',
  'This is a required field! Please enter your telephone number, formated as "0__-___-__-__"',
  'This field is required and has to contain 2-32 cyrillic characters',
  'This is a required field! It has to contain from 5 to 30 latin characters and "_"',
  'This is a required field!',
  'This is a required field!',
  'This field has to contain from 1 to 10 latin characters or numbers.'];

  public statusArr : string[] = [];

  constructor(private storageService: storageService) { }

  ngOnInit() {
    this.signUpForm = new FormGroup({
      'firstName': new FormControl(null, [Validators.required, Validators.pattern(/^[а-яА-ЯёЁіІїЇ]{2,32}$/iu)]),
      'email': new FormControl(null, [Validators.required, Validators.email, Validators.pattern(/^\S{2,255}@\S+\.\S+$/iu)]),
      'country': new FormControl(null, Validators.required),
      'phone': new FormControl(null),
      'lastName': new FormControl(null, [Validators.required, Validators.pattern(/^[а-яА-ЯёЁіІїЇ]{2,32}$/iu)]),
      'id': new FormControl(null, [Validators.required, Validators.pattern(/\b[A-Za-z_]{5,30}\b/)]),
      'state': new FormControl(null, Validators.required),
      'city': new FormControl(null, Validators.required),
      'code': new FormControl(null, [Validators.pattern(/\b[A-Za-z_0-9]{1,10}\b/)])
    });

    if(this.storageService.savedForm) this.signUpForm.setValue(this.storageService.savedForm);
  }

  onSubmit() {
    if(this.signUpForm.status === 'VALID') {
      this.storageService.savedForm = this.signUpForm.value;
      console.log(this.signUpForm);
    } else {
      let namesArr = Object.keys(this.signUpForm.controls);
      console.log(namesArr);
      for(let i = 0; i < namesArr.length; i++) {
        this.statusArr.push(this.signUpForm.controls[namesArr[i]].status);
      }
      console.log(this.statusArr);
    }
  }

  onReset() {

  }

  onChange() {
   (<FormGroup>this.signUpForm.get('state').value) = null;
   (<FormGroup>this.signUpForm.get('city').value) = null;
  }

  onOpen(controlName: string) {
  }
}
从'@angular/core'导入{Component,OnInit,ViewChild,ElementRef};
从“@angular/forms”导入{FormGroup、FormControl、FormArray、Validators};
从“../storage service.component”导入{storageService};
@组成部分({
选择器:“应用程序窗体”,
templateUrl:'./form.component.html',
样式URL:['./form.component.scss']
})
导出类FormComponent实现OnInit{
报名表格:FormGroup ;;
国家=[
新FormControl(“美国”),
新FormControl(“印度”)
];
statesUSA=[new FormControl('new York')、new FormControl('California');
statesIndia=[新FormControl('Andhra Pradesh')、新FormControl('Goa')]
citiesNY=[新表单控制(“奥尔巴尼”)、新表单控制(“纽约市”);
citiesCali=[新表单控制(“萨克拉门托”)、新表单控制(“洛杉矶”)、新表单控制(“旧金山”)];
citiesAndhra=[new FormControl('Visakhapatnam')、new FormControl('Amaravati');
citiesGoa=[new FormControl('Panaji')、new FormControl('Vasco da Gama');
@ViewChild('phoneInput',{static:false})phoneInput:ElementRef;
公共掩码:任何={
掩码:'+{38}(0___)000-00-00',
懒惰:错
}
invalidMessages=['此字段是必需的,必须包含2-32个西里尔字符!',
'此字段是必填字段,必须是有效的电子邮件地址!',
'这是必填字段!',
'这是必填字段!请输入您的电话号码,格式为“0 \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \”格式',
'此字段为必填字段,必须包含2-32个西里尔字母',
'这是必填字段!它必须包含5到30个拉丁字符和“33;”,
'这是必填字段!',
'这是必填字段!',
“此字段必须包含1到10个拉丁字符或数字。”];
公共状态:字符串[]=[];
构造函数(私有存储服务:存储服务){}
恩戈尼尼特(){
this.signUpForm=新表单组({
“firstName”:新的FormControl(null,[Validators.required,Validators.pattern(/^[а-ЯА-ЯёіїЇ]{2,32}$/iu)],
“电子邮件”:新的FormControl(null,[Validators.required,Validators.email,Validators.pattern(/^\S{2255}@\S+\.\S+$/iu)],
“国家”:新FormControl(空,验证器。必需),
“电话”:新FormControl(空),
“lastName”:新的FormControl(null,[Validators.required,Validators.pattern(/^[а-ЯА-ЯёіїЇ]{2,32}$/iu)],
'id':新FormControl(null,[Validators.required,Validators.pattern(/\b[A-Za-z!]{5,30}\b/)),
“状态”:新FormControl(null,Validators.required),
“城市”:新的FormControl(null,Validators.required),
“代码”:新FormControl(null,[Validators.pattern(/\b[A-Za-z_0-9]{1,10}\b/))
});
if(this.storageService.savedForm)this.signUpForm.setValue(this.storageService.savedForm);
}
onSubmit(){
if(this.signUpForm.status=='VALID'){
this.storageService.savedForm=this.signUpForm.value;
console.log(this.signUpForm);
}否则{
让namesArr=Object.keys(this.signUpForm.controls);
console.log(namesArr);
for(设i=0;i
试试下面的方法,我已经为一个表单控件单独做过了,如果它对所有其他控件都有效的话。 在HTML中

<div class="form__control form__first-name">
    <input type="text" name="Fname" required formControlName="firstName" a-ngblur="onBlur(true)">
    <label>First Name</label>
    <span *ngIf="firstname.errors.required && firstname.touched">This field is required</span>
    <span *ngIf="firstname.errors.pattern && firstname.touched">Pattern not matching</span>
</div>
get firstName(){
    this.signUpForm.get('firstName')
}
<span *ngIf="signupForm.get('firstname').errors.required && signupForm.get('firstname').touched">This field is required</span>
<button [disabled]="signupForm.invalid">Submit form</button>