使用formControlName作为json键路径的Angular Reactive表单验证

时间:2019-03-26 06:59:34

标签: angular6 angular-reactive-forms

在我的表单中,我必须使用firstName[0].value作为formControlName,它想获取值作为键,并且还需要通过简单的必需验证来验证输入字段

Forms.conponent.html:

    <form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
     <div class="form-group">
      <label>Name</label>
        <input type="text" formControlName="firstName" class="form-control [ngClass]="{ 'is-invalid': submitted && 
       f.firstName[0].value.errors }" />
  <div *ngIf="submitted && f.firstName[0].value.errors" 
       class="invalid-feedback">
    <div *ngIf="f.firstName[0].value.errors.required">First Name is 
     required</div>
      </div>
        </div>
        <div class="form-group">
       <button class="btn btn-primary">Register</button>
       </div>
      </form>

Forms.component.ts:

 registerForm: FormGroup;
  submitted = false;

constructor(private formBuilder: FormBuilder) { }

ngOnInit() {
    this.registerForm = this.formBuilder.group({
        'firstName[0].value': ['', Validators.required],
    });
}

// convenience getter for easy access to form fields
get f() { return this.registerForm.controls; }

onSubmit() {
    this.submitted = true;

    // stop here if form is invalid
    if (this.registerForm.invalid) {
        return;
    }

    alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.registerForm.value))
}

我的问题是将firstName[0].value用作变量进行验证以及如何在ngIf中使用它?

0 个答案:

没有答案