Angular *ngIf 用于嵌套的表单组值

Angular *ngIf for nested formgroup value

我想为某些 div...

实现 *ngIf

无效:

*ngIf="postForm.value.osnovne.sekcija === vozila"

还有

*ngIf="postForm.controls['osnovne'].value.sekcija === vozila

这是我的表格:

this.postForm = this.fb.group({
      osnovne: this.fb.group({
        sekcija: vozila,
        cena: "",
        dogovor: "",
        opis: ""
      }),
      detaljne: this.fb.group({
        name: "",
        value: ""
      }),
      imagePath: this.fb.group({
        data: ""
      })
    });

怎么办?

你需要更好地使用 .get(),像这样:

*ngIf="postForm.get('osnovne').get('sekcija').value === vozila"

.get() 将确保您始终获得值,即使控件被禁用

使用 ngx-sub-form 库可以更轻松地将您的表单分解为子表单组件,它看起来如下所示:

<form [formGroup]="formGroup">
    <app-osnovne-form [formControlName]="formControlNames.osnovne"></app-osnovne-form>
</form>

<div *ngIf="formGroupValues.osnovne?.sekcija === 'vozila'; else noVozila">
  "vozila" is the current value of osnovne.sekcija
</div>

<ng-template #noVozila>
  "vozila" is not the current value of osnovne.sekcija
</ng-template>

<pre>{{ formGroupValues | json }}</pre>

这是一个现场演示:https://stackblitz.com/edit/so-answer-angular-ngif-for-nested-formgroup-value?file=src/app/form/form.component.html

编辑:

如果你想更进一步,我刚刚发布了一篇博客 post 来解释很多关于表单的事情,ngx-sub-form 这里 https://dev.to/maxime1992/building-scalable-robust-and-type-safe-forms-with-angular-3nf9