1

Good day. I have a problem with figuring out how to handle form validation with appropriate styling when there are nested forms. The thing that I want to accomplish is the following: I have a Page, on this page I'm showing the Tabs components with four tabs in it. Each tab is the separate @Page. The one page that I'm currently working on has a list of some components (ItemListCmp). Each individual components (let's call it ItemCmp) has a form. This form should be validated and in the case of invalid state do something with the styling of ItemCmp. The ItemListCmp also has a form that wraps this bunch of ItemCmp components and should also be notified somehow, when the status of the sum of all inner forms (ItemCmp) changes.

Could you help me with this, or point some source of information related to this question. Thank you

enter image description here

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
Paul Seleznev
  • 672
  • 1
  • 11
  • 24

2 Answers2

2

I would create ngForm / ngControl compatible components for ItemListCmp and ItemCmp. This way you could leverage their status through the valid property and also apply some validation. You would be able to add each component as a control within the containing form at each level.

The following article will give some hints about how to implement this in its section "NgModel-compatible component":

This question could also give you more details:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
0

I've done this by using @ViewChildren decorator. To put it simply - in my ItemListCmp I'm creating the form(but without the "form" html tag) dynamically in AfterViewInit component lifecycle callback

// somewhere at the class ItemListCmp
@ViewChildren(ItemCmp) itemCmps: QueryList<ItemCmp>;


ngAfterViewInit() {
const iCmps = this.itemCmps.toArray();
iCmps.map((c: ItemCmp, key: number) => {
  this.listForm.addControl(key.toString(), c.itemForm);
});
this.listForm.statusChanges
  .debounce(() => Observable.timer(800))
  .distinctUntilChanged()
  .subscribe((status: string) => {
  if (status === 'VALID') {
    this.onStatusChanged.emit(1);
  } else {
    this.onStatusChanged.emit(0);
  }
});
}

http://blog.mgechev.com/2016/01/23/angular2-viewchildren-contentchildren-difference-viewproviders/ helps me a lot

Paul Seleznev
  • 672
  • 1
  • 11
  • 24