0

I have the following form-modal component:

<div class="modal-header">
    <h4 class="modal-title">{{title}}</h4>
    <button type="button" class="close" aria-label="Close"
     (click)="activeModal.dismiss('Cross click')">
    </button>
</div>

<ng-content #form></ng-content>

<div class="modal-footer">
    <button class="btn btn-primary btn-danger" (click)="onCancel()">
        Cancel
      </button>
    <button class="btn btn-primary btn-success" type="submit" form="formModal" [disabled]="form.formModalGroup?.invalid">
        Save
      </button>
</div>

ng-content itself holds the specific form. The question is how to get the formGroup validity status from the ng-content to this parent form-modal component. I have tried bubbling an event from the specific form component, also @ContentChild, and I also have come up with this very similar question:

Disable/Enable submit button in parent component when forms are in child component

But that fix doesn't seem to work when adding the reference directly to the ng-content tag.

2 Answers2

0

It should work with a @ContentChild, in your TS :

@ContentChild(YourComponentType, {static: true}) childComponent:YourComponentType;

In your HTML:

[disabled]="!childComponent || childComponent.formModalGroup?.invalid"
Michael Desigaud
  • 2,115
  • 1
  • 15
  • 15
  • Yes, I've already tried this. It was my first choice actually. But it continues saying that it cannot read property formModalGroup of undefined. – Nicolás Kruk Oct 25 '19 at 15:04
  • yes maybe because when the component is initializing it is not defined yet. Maybe add this extra condition: [disabled]="!childComponent || childComponent.formModalGroup?.invalid" – Michael Desigaud Oct 25 '19 at 15:11
0

As I've seen on your code, you are facing a common problem where we all have been: communicating between parent/child/siblings...

If you want to react to changes in the validity of the form in your TS file, I could see 2 main options:

  • Use @ContentChild:
@ContentChild("form", {static: false}) form;

ngAfterContentInit() {
    // here now you can access to the form instance, and subscribe to changes on the status
    this.form.statusChanges.subscribe(
        result => console.log(result)
    );

  }

Full example on this answer: https://stackoverflow.com/a/49666202/6852402

  • Consider using a shared service between 2 components, and make use of a BehaviorSubject observable. BehaviorSubject is the foundation of state libraries based on RxJs.

Here you can see a full explanation and example: https://medium.com/@weswhite/angular-behaviorsubject-service-60485ef064fc

MigueMike
  • 189
  • 6