【问题标题】:How to disable/enable submit button in parent component when form is in its ng-content当表单在其ng-content中时如何禁用/启用父组件中的提交按钮
【发布时间】:2019-10-25 14:02:28
【问题描述】:

我有以下表单模式组件:

<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 本身具有特定的形式。问题是如何从 ng-content 获取 formGroup 的有效性状态到这个父 form-modal 组件。我已经尝试从特定的表单组件中冒泡一个事件,也就是@ContentChild,我也提出了这个非常相似的问题:

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

但是当直接将引用添加到 ng-content 标记时,该修复似乎不起作用。

【问题讨论】:

    标签: angular angular-reactive-forms


    【解决方案1】:

    它应该在您的 TS 中与 @ContentChild 一起使用:

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

    在您的 HTML 中:

    [disabled]="!childComponent || childComponent.formModalGroup?.invalid"
    

    【讨论】:

    • 是的,我已经尝试过了。这实际上是我的第一选择。但它继续说它无法读取未定义的属性 formModalGroup。
    • 是的,可能是因为当组件初始化时它还没有定义。也许添加这个额外的条件:[disabled]="!childComponent || childComponent.formModalGroup?.invalid"
    【解决方案2】:

    正如我在您的代码中看到的那样,您面临着一个我们都遇到过的常见问题:父母/孩子/兄弟姐妹之间的沟通......

    如果您想对 TS 文件中表单有效性的更改做出反应,我可以看到 2 个主要选项:

    • 使用@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)
        );
    
      }
    

    此答案的完整示例:https://stackoverflow.com/a/49666202/6852402

    • 考虑在 2 个组件之间使用共享服务,并使用 BehaviorSubject observable。 BehaviorSubject 是基于 RxJs 的状态库的基础。

    在这里你可以看到完整的解释和例子:https://medium.com/@weswhite/angular-behaviorsubject-service-60485ef064fc

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-19
      • 2016-04-03
      • 2019-09-27
      • 2019-01-03
      • 2010-09-11
      • 1970-01-01
      相关资源
      最近更新 更多