-2

I am new to angular. I have to two component, one is parent and another is child component. Parent component has a Modal. Child component is a form which is open in the parent component's Modal. Now I would like to know how can I submit the child component form when clicking on parent component Modal's OK button.

mnu-nasir
  • 1,642
  • 5
  • 30
  • 62

1 Answers1

2

each time you wanna handle action in child component from parent component like submit you have two choice one create service and subscribe to the actionStatus property

export class CtrlActionService {
  private actionStatus = new Subject<any>();

  constructor() {}

  //ctrl submit action
  public callAction() {
    this.actionStatus.next(true);
  }
  public getAction(): Observable<boolean> {
    return this.actionStatus.asObservable();
  }
}

parent.component.ts

onClickOkButton() {
  this.ctrlActionService.callAction()
}

child.component.ts

ngOnInit() {
  this.ctrlActionService.getAction().subscribe(r => {
    if (r) {
      // your code
    }
  })
}

////////////////////////////////////////////////

or can do another way with call child component method from parent component by create ViewChild

parent.component.html

<child #childComponent></child>

parent.component.ts

@ViewChild('childComponent') childComponent: childComponent;
onClickOkButton() {
  this.childComponent.doAction();
}

child.component.ts

doAction() {
      // your code
}

i only know these two way and hope useful to you

mehranmb78
  • 674
  • 5
  • 9