【问题标题】:Submit child component from parent component modal ok button in angular [duplicate]从有角度的父组件模态ok按钮提交子组件[重复]
【发布时间】:2021-04-08 08:58:14
【问题描述】:

我是 Angular 的新手。我有两个组件,一个是父组件,另一个是子组件。父组件有一个 Modal。子组件是在父组件的 Modal 中打开的表单。现在我想知道如何在点击父组件Modal的OK按钮时提交子组件表单。

【问题讨论】:

    标签: angular bootstrap-modal angular-components


    【解决方案1】:

    每次您想从父组件处理子组件中的操作(例如提交)时,您有两个选择,一是创建服务并订阅 actionStatus 属性

    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
        }
      })
    }
    

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

    或者可以通过创建ViewChild从父组件调用子组件方法来做另一种方式

    parent.component.html

    <child #childComponent></child>
    

    parent.component.ts

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

    child.component.ts

    doAction() {
          // your code
    }
    

    我只知道这两种方式,希望对你有用

    【讨论】:

      猜你喜欢
      • 2020-06-18
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 2020-09-02
      • 2020-05-14
      • 2022-07-07
      相关资源
      最近更新 更多