将控件添加到动态Angular反应形式

时间:2019-08-16 01:53:14

标签: angular

我有一个像这样动态创建的Angular反应形式:

  this.reportForm = this.fb.group({
    dwellingValues: this.fb.group({
      design: [this.report.design],
      foundation: [this.report.foundation],
      age: [this.report.age],
    }),
  });

如何向dwellingValues formGroup添加控件?

我尝试过:

this.reportForm.addControl('dwellingValues', this.fb.group({ reportDate: [this.report.beingRenovated, Validators.required] }))

this.reportForm.dwellingValues.addControl('dwellingValues', this.fb.group({ reportDate: [this.report.beingRenovated, Validators.required] }))

2 个答案:

答案 0 :(得分:0)

您需要先获得dwellingValuesGroup

const dwellingValuesGroup = this.reportForm.get('dwellingValues') as FormGroup;

然后您可以轻松地向该FormGroup添加任何控件:

const controlToAdd = new FormControl(this.report.beingRenovated, Validators.required);

dwellingValuesGroup.addControl('reportDate', controlToAdd);

答案 1 :(得分:0)

您应该尝试使用这种反应形式。 file.html

<div class="login">
<h2 class="login-header">Log in</h2>
 <form [formGroup]="loginForm" class="login-container" (ngSubmit)="login()">

  <p [ngClass]="{ 'has-error': isSubmitted && formControls.email.errors }">
  <input type="email" placeholder="Email" formControlName="email">
  </p>

<div *ngIf="isSubmitted && formControls.email.errors" class="help-block">
  <div *ngIf="formControls.email.errors.required">Email is required</div>
</div>

<p [ngClass]="{ 'has-error': isSubmitted && formControls.password.errors }">
  <input type="password" placeholder="Password" formControlName="password">
</p>

<div *ngIf="isSubmitted && formControls.password.errors" class="help-block">
  <div *ngIf="formControls.password.errors.required">Password is 
  required</div>
</div>

   <p>
    <input type="submit" value="Log in">
   </p>
 </form>
</div>

file.component.ts

 //import this 
  import { FormBuilder, FormGroup, Validators } from  '@angular/forms';
  import { Router } from  '@angular/router';
  import { User } from  '../user';
  import { AuthService } from  '../auth.service';

export class LoginComponent implements OnInit {
 constructor(private authService: AuthService, private router: Router, private formBuilder: FormBuilder ) { }

ngOnInit() {
  this.loginForm  =  this.formBuilder.group({
    email: ['', Validators.required],
     password: ['', Validators.required]
    });
  }
}

在下面的链接中您有一些清晰的主意。 https://www.techiediaries.com/angular-tutorial-reactive-forms/

相关问题