Variable Sharing between Angular Components

Asked

Viewed 31 times

0

How do I use variables from an Angular component in the following context? In a component I have a variable that is an array of a class created in that same component, this variable controls the selected items in a list, follows the component code:

test: ClasseCriada[]

In the HTML of this same component I speak an Ngif to take the selected items and change the display, thus test.length >= 1

It turns out that I have to use this same Ngif in another component, but HTML accuses error that the length property cannot be accessed because it is not a property.

Trying to solve I used the decorators @Output and @Input but it didn’t work because they are components that are in the same hierarchy and not father and son.

1 answer

0


In this case you can use the parent component to share the data between siblings.

The component where you manipulate the list would be as follows:

@Output() testChanged = new EventEmitter<ClasseCriada[]>();
test: ClasseCriada[];

addToTest() {
  //insere no array
  this.testChanged.emit(this.test);
}

The component where you should receive this list would look like this:

@Input() test: ClasseCriada[];

The parent component would look like this:

HTML

<a-component (testChanged)="onTestChanged($event)"></a-component>
<b-component [test]="test"></b-component>

TS

test: ClasseCriada[];

onTestChanged(data:ClasseCriada[]) {
  this.test = data;
}

You can take a look at this link 5 Ways to share data between Angular

Browser other questions tagged

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