score:1

Accepted answer

i'll try to be as brief as possible:

there are many ways you can communicate between components. the ones that you mentioned (using the @input() and @output decorators) are basically as follows:

@input() - receives data from parent

this is as simple as it gets. you pass data to the child component like so:

<!-- one-way binding - value moves from the parent to child -->
<app-custom-component [childvar]="parentvar" ></app-custom-component>

and declare it in the child component's .ts like so:

// you will have to import input from @angular/core
@input() childvar: string;

@output() - sends data to parent

it behaves just like an event. in fact, it is an event:

// import output and eventemitter from @angular/core as well
@output childchange: new eventemitter<string>();

then the parent has to listen to it:

<!-- the $event carries the content you want to grab -->
<app-custom-component2 (childchange)="parentdoessomething($event)"></app-custom-component2>

docs here.

with this, you can receive data from one component in the parent and send it to another. there are other ways you can communicate between components, like with services.

actually, take a look at this article. it covers a lot of stuff.

example using @input() and @output()

i made a quick little example in stackblitz. check it out in case you're having trouble implementing it.


Related Query

More Query from same tag