Filu
Filu

Reputation: 45

How can I disable a button thats in a different component in Angular?

I have this component structure: i have a dialog which has an "add" button a rendered form from the child component(structure above)

I am trying to make the button disabled untill the child component( the form) is valid. When the form is valid; the button becomes enabled.

structure:

<ng-container >
  <add-action-form
    [patches]="this.config.data"
  >
  </add-action-form>

  <div class="p-dialog-footer">
    <button
      pButton
      class="p-button-secondary p-button-text"
      [label]="cancel"
      (click)="onCancel()"
    ></button>
    <button
      pButton
      [label]="add action"
      (click)="onAddAction()"
    ></button>
  </div>
</ng-container>

Upvotes: 0

Views: 380

Answers (1)

Pankaj Prakash
Pankaj Prakash

Reputation: 2428

If you are using reactive forms you can subscribe to the value changes of the form and emit an event back stating form is valid or not.

Here is an example.

add-action-form.component.ts

// some code

form: FormGroup();

@Output()
valueChanged = new EventEmitter<boolean>();

ngOnInit() {

  this.form.valueChanges.subscribe(_ => valueChanged.emit(this.form.valid));
}

// some more code
<ng-container >
  <add-action-form
    [patches]="this.config.data"
    (valueChanged)="addActionFormValid = $event"
  >
  </add-action-form>

  <div class="p-dialog-footer">
    <button
      pButton
      class="p-button-secondary p-button-text"
      [label]="cancel"
      (click)="onCancel()"
      [disabled]="!addActionFormValid"
    ></button>
    <button
      pButton
      [label]="add action"
      (click)="onAddAction()"
      [disabled]="addActionFormValid"
    ></button>
  </div>
</ng-container>

Upvotes: 1

Related Questions