0

I've uploaded my problem to a stackblitz.

I have a site which has multiple forms, accessible through routing. I'm centralizing the submission logic in a parent component. A single click should submit all of the forms.

Is there a way to access the form element (in order to check its' validity), located on a child route, without using a dedicated service?

Thanks

noamyg
  • 2,747
  • 1
  • 23
  • 44
  • 1
    No, when you "route" to another component, you loose the data of the component. It's the reason because you need store the values in a service (a service lives all the time). You can re-thinking your app, using a parent component with childs -but not in ``- an object with all the properties belong to the main component and pass as input to the child this object -remember that if you pass as input an object, you can change the properties with not necesary event emitter. but then you don't route, only show one or another child using `*ngIf` – Eliseo Sep 01 '19 at 10:20
  • Thanks @Eliseo, how would you inject the whole form to a service? NgModel doesn't seem to work – noamyg Sep 01 '19 at 11:07
  • I added a response, I hope this help you – Eliseo Sep 01 '19 at 11:57

1 Answers1

1

imagine you has a simpleService

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class DataService {
  data:any={}
  constructor() { }
}

a componet can be like, see that in [(ngModel)] we are using data.nameOfPropertie

<form ngNativeValidate #f1="ngForm">
  <div>
    <label for="username">User Name: </label>
    <input [(ngModel)]="data.username" class="form-control" type="text" name="usrname" required>
  </div>
  <div>
    <label for="phonenum">Phone: </label>
    <input [(ngModel)]="data.phonenum" class="form-control" name="phonenum" type="tel" pattern="^\d{4}-\d{3}-\d{4}$" required>
  </div>
  </form>

Your component.ts like

export class Form1Component  {
  get data()
  { 
    return this.dataService.data;
  }
  set data(value)
  {
     this.dataService.data=value
  }
  constructor(private dataService:DataService){}
}

each component that inject the DataService, can access to this.dataService.data

See your forked stackblitz

NOTE1: If you choose ReactiveForms, the tecnica is similar, you share the data, and change it subscribing to myForm.valueChanges

NOTE2: For most complex form, we can use Subject and emit Value, see my response in SO question

Eliseo
  • 50,109
  • 4
  • 29
  • 67
  • That's what I ended up doing, but instead of saving the model to `data`, I stored a copy of the form element (because I want to know the state of the form. not only its' inputs). Thank you – noamyg Sep 01 '19 at 13:19