-1

我需要一些关于如何思考这个问题的帮助..

我有结帐组件,它只是一个表单(public cartForm = new FormGroup({});)并且有使用 ControlValueAccessors 的子组件......所以表单结构变成

-checkout
--address
--articles(array)
---article (each looped item)

地址/成本中心的东西正在工作..但是在文章组件中,我为每个项目都有一个 ngFor ,现在我需要添加一个控件,但这是我卡住的地方......

// Parent Component
<form [formGroup]="cartForm">
  <ssp-checkout-articles-list [articles]="cart.articles"></ssp-checkout-articles-list>

  <!-- <ssp-delivery-address></ssp-delivery-address> -->
  <!-- <ssp-cost-center></ssp-cost-center> -->

  <div fxLayout="row" fxLayoutAlign="end center">
    <button mat-button type="submit" [disabled]="!cartForm.valid">Place Order</button>
  </div>
</form>
// The list
<ng-container formArrayName="articles">
  <ssp-checkout-article
    *ngFor="let article of articles"
    [article]="article"
    fxLayout="row"
  ></ssp-checkout-article>
</ng-container>

// TS
    this.articlesForm = this.parent.form;
    this.articlesForm.addControl('articles', new FormArray([]));

    this.articles.forEach((article) => {
      (this.articlesForm.get('articles') as FormArray).push(
        new FormGroup({
          article: new FormGroup({
            approved: new FormControl(false, [Validators.requiredTrue])
          })
        })
      );
    });
// The article component
<ng-container [formGroup]="articleForm">
  <div class="article" fxLayout="row">
    <div class="info" fxLayout="column">
      <div
        class="mat-h4 name">{{ article.name }}
      </div>
      <div class="terms">
        <mat-checkbox color="primary">approve</mat-checkbox>
      </div>
    </div>
  </div>
</ng-container>

 // TS
 this.articleForm.addControl('article', new FormControl(new FormGroup({
    article: new FormGroup({
      approved: new FormControl(false, [Validators.requiredTrue])
    })
  })));
4

1 回答 1

0

在 StackBlitz 上查看此示例

以下是您的表单应该如何初始化 -

form = new FormGroup({
    address: new FormGroup({}),
    articles: new FormArray([])
   });

然后将articlesformArray 绑定到您的模板中,如下所示 -

<form name="form" [formGroup]="form">
  <app-articles [articles]="form.get('articles')">
</app-articles>
</form>

articles零件 -

@Component({
  selector: 'app-articles',
  template: `
  <ng-container >
  
     <app-article *ngFor="let article of articles.controls" [article]="article">
     </app-article>
     </ng-container>
     <input type="text" [(ngModel)]="inputArticle" />
<button (click)="addArticle()">Add Article</button>
  `,
  styles: []
})
export class Articles implements OnInit {
  inputArticle;
@Input() articles: FormArray;
}

最后,您的article组件 -

@Component({
  selector: 'app-article',
  template: `
     <ng-container>
     <div>
      {{article.get('description').value}}
      </div>
     </ng-container>
  `,
  styles: []
})
export class Article implements OnInit {
@Input() article: FormGroup;
    ngOnInit() {
    }
}
于 2020-09-21T10:34:03.560 回答