【问题标题】:How to access the value of a FormControl in a Child Component for the Parent Component?如何访问父组件的子组件中 FormControl 的值?
【发布时间】:2019-08-30 21:20:20
【问题描述】:

我的 Angular 应用有一个父组件和几个子组件。

我的父组件中有一个禁用 OnInit 的“提交”按钮。只有在选中其中一个子组件中的复选框时才启用它。 如果未选中该复选框,则该按钮应保持禁用状态。

这是我的父组件 HTML。如果未选中该复选框,我将尝试禁用该按钮:

<form [formGroup]="emailForm" (ngSubmit)="onSubmit()" class="form-horizontal">
    <app-conditions (formReady)="formInitialized('conditions', $event)"></app-conditions>
    <app-damage-details-one (formReady)="formInitialized('damageDetailsOne', $event)"></app-damage-details-one>
    <app-damage-details-two (formReady)="formInitialized('damageDetailsTwo', $event)"></app-damage-details-two>
    <app-personal-info></app-personal-info>
    <app-send></app-send>

    <card>
        <card-footer>
            <button button class="axis-btn" type="submit" title="Confirm and send" data-kind="primary"
[disabled]="emailForm.conditions.acceptTerms.checked === false">Confirm and send</button>
        </card-footer>
    </card>
</form>

我试图引用的复选框位于下方 (conditions.component.html)。

app-conditions 在 my Parent 中指的是这个孩子:

<div [formGroup]="conditionsForm">
    <card>
        <card-body>
            <div class="form-group">
                <label class="control-label" for="Accept">{{lblAccept} </label>
                <checkbox formControlName="acceptTerms" cid="Accept" heading="Accept" name="Accept" value="Accept">
                </checkbox>
            </div>
        </card-body>
    </card>
</div>

有人可以告诉我需要做哪些更改,以便我可以根据子项中的复选框是否被选中来启用/禁用父项中的按钮?非常感谢

【问题讨论】:

    标签: angular


    【解决方案1】:

    使用 Angular Output 属性

    按照官方角度documentation

    子组件公开一个 EventEmitter 属性,当发生某些事情时,它会使用该属性发出事件。父级绑定到该事件属性并对这些事件做出反应。

    【讨论】:

      【解决方案2】:

      我使用以下代码更新了我的父组件:

      <button axis-button class="axis-btn" type="submit" title="Confirm and send" data-kind="primary"
          [disabled]="emailForm.controls['conditions'].controls['acceptTerms'].value === false">Confirm
          and send</button>
      

      父组件按钮现在只有在子组件的复选框被选中时才会启用。

      【讨论】:

        【解决方案3】:

        以下是您在子组件中需要在选中复选框时捕获并在父组件中捕获的内容

        更多信息:https://angular.io/guide/component-interaction

          1)@Output() change: EventEmitter<string> = new EventEmitter<string>();
        
            2)Also add a method that emits change when checkboxchange event occurs
                OnCheckBoxChecked(value: string) {
                        this.change.emit(value);
                    }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-11-12
          • 2016-12-24
          • 2019-12-29
          • 2016-10-05
          • 1970-01-01
          • 2015-04-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多