Access an accordion variable from a child component to the parent

Asked

Viewed 29 times

1

I need to access from a child component the accordion expander that lies in the parent component, its name is isExpandend

On the child component, when clicking the save button, it should include a new service, and expand the accordion where this new service was added.

In the parent component I already use isExpandend to filter the services and expand the accordion.

This is the HTML Parent code

<mat-accordion class="agregador-pesquisa__accordion mat-accordion" [multi]="isExpanded">
    <mat-expansion-panel class="mat-expansion-panel" mat-expanded="true"
   </mat-expansion-panel>
</mat-accordion

Component Pai TS

public isExpanded: boolean;

NOTE: I put only one piece of code to facilitate understanding. I just want to know if it is possible to access the isExpanded variable.

1 answer

2


It is possible using @Input and @Output. As in this example, taken from the documentation:

Child component - TS:

import { Output, EventEmitter } from '@angular/core';

export class ItemOutputComponent {
  @Output() newItemEvent = new EventEmitter<string>();

  addNewItem(value: string) {
    this.newItemEvent.emit(value);
  }
}

Parent component - TS:

export class AppComponent {
  items = ['item1', 'item2', 'item3', 'item4'];

  addItem(newItem: string) {
    this.items.push(newItem);
  }
}

Parent component - TEMPLATE:

<app-item-output (newItemEvent)="addItem($event)"></app-item-output>
  • Then in case it would be (newItemEvent)="isExpanded($Event)". With this I could manipulate the way I want isExapnded using Output, right ?

  • In fact the addItem must be a method, and it update the property isExpanded.

  • For example, in the parent component, create the method updateExpanded(val: string) { this.isExpanded = val }. And in the template would be (newItemEvent)="updateExpanded($event)

  • I get it. Thank you !!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.