1

I have the following component template

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

<section>
  <mat-form-field>
    <input matInput formControlName="firstName" placeholder="First name" />
  </mat-form-field>
</section>

<child-component [form]="form"></child-component>

<button type="submit" mat-raised-button color="primary">
  <span>Submit</span>
</button>

</form>

And the following child component template

<section [formGroup]="form">
  <mat-form-field>
    <input matInput formControlName="emailAddress" placeholder="Email address" />
  </mat-form-field>
</section>

Both fields are defined using reactive approach in the parent component and set as required.

When submitting the form, only the field inside the parent component has class mat-form-field-invalid and is shown in red.

Both fields appear as invalid at FormControl instance though.

I have created the following stackblitz to reproduce the issue https://stackblitz.com/edit/angular-material2-issue-7x45bp

mopicus
  • 31
  • 5

2 Answers2

1

The easiest way to do this is to pass in the FormControl instead of the form:

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

  <section>
    <mat-form-field>
      <input matInput formControlName="firstName" placeholder="First name" />
    </mat-form-field>
  </section>

  <child-component [childControl]="form.get('emailAddress')"></child-component>

  <button type="submit" mat-raised-button color="primary">
    <span>Submit</span>
  </button>

</form>


<section>
  <mat-form-field>
    <input matInput [formControl]="childControl" placeholder="Email address" />
  </mat-form-field>
</section>

This is actually better for component re-usability anyway (if you also make placeholder a property).

Otherwise, you would probably need to have your child component implement ControlValueAccessor.

G. Tranter
  • 16,766
  • 1
  • 48
  • 68
0

If I'm not mistaken, your invalid form fields will only appear in red after they have been marked as touched, which you can force programtically on form submit if you so wish (just not so elegant, Reactive Forms - mark fields as touched).

Your required fields are missing the asterisk that usually exists next to the form field name to visually indicate that the field is required. To add that just add required="true" or alternatively [required]="someFunctionThatChecksFieldHasRequiredValidatorInFormGroup(fieldName)"

Joseph Simpson
  • 4,054
  • 1
  • 24
  • 28
  • The required flag is set when initializing the formGroup for both fields. I expect that both fields behave the same, but you can see in the stackblitz that only first one works as expected, i.e. is shown in red after submit – mopicus May 08 '18 at 08:58
  • Understood. My answer stands. Good luck – Joseph Simpson May 08 '18 at 09:57