角反应形式验证嵌套字段

时间:2019-06-22 16:26:45

标签: angular angular-reactive-forms

我正在使用 Angular 7

我有一个嵌套的反应形式

   function showProfile($user)
    {
        global $connection;

        $query = $connection->prepare("SELECT * FROM profiles WHERE user = :user ");
        $query->bindValue(':user', $user);

        $result =  $query->execute();

        echo "<table width='398' border='0' align='center' cellpadding='0'>
                  <tr><td height='26' colspan='2'>Your Profile Information </td>
                  </tr> ";

        /* associative array */  
        while($row = $result->fetch_array(MYSQLI_ASSOC))
        {
            echo "
                  <tr>
                      <td width='82' valign='top'><div align='left'>FirstName:</div></td>
                      <td width='165' valign='top'>{$row['forename']}</td>
                   </tr>
                   <tr>
                      <td valign='top'><div align='left'>LastName:</div></td>
                      <td valign='top'>{$row['surname']}</td>
                   </tr>";
        }

        echo "</table>";
    }

我有类似HTML的表单

this.salonProfileForm = this.fb.group({
  salonName: new FormControl('', [Validators.required]),
  address: this.fb.group({
    city: new FormControl('', [Validators.required])
  })
});

get f() {
    return this.salonProfileForm.controls;
}

但这在城市输入 ng-container 字段上显示为错误

<input type="text" formControlName="salonName" required />
<ng-container *ngIf="submitted && f.salonName.invalid && (f.salonName.dirty || f.salonName.touched)">
   <small *ngIf="f.salonName.errors.required">
      Salon name is required
   </small>
</ng-container>

<div formGroupName="address">
  <input type="text" formControlName="city" />
  <ng-container *ngIf="submitted && f.city.invalid && (f.city.dirty || f.city.touched)">
    <small *ngIf="f.city.errors.required">
        city is required
    </small>
  </ng-container>
</div>

如何验证嵌套的输入字段?

  

console.log(this.f.address)

enter image description here

1 个答案:

答案 0 :(得分:1)

您必须按以下方式访问:

f.address.controls.city.invalid

修改

export class Home implements OnInit {
  salonProfileForm : FormGroup;

  ngOnInit() {
    this.salonProfileForm = new FormGroup({
      'salonName': new FormControl('', [Validators.required]),
      'address': new FormGroup({
        'city': new FormControl('', [Validators.required])
    })
  });
 }

}

移动到.html模板

<form [formGroup]="salonProfileForm " (ngSubmit)="onSubmit()">

<div formGroupName="address">
  <input type="text" formControlName="city" />
  <ng-container *ngIf="!salonProfileForm.get('address.city').valid && salonProfileForm.get('address.city').touched">
    <span>This is required</span>
  </ng-container>
</div>

</form>

我已经粘贴了它可以工作的形状,所以随时更新代码以适合上面的情况。