Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

typescript - Angular 2 - How do you call a function in a sibling component?

I have 2 sibling components that need to communicate:

<app-controls></app-controls> <app-main></app-main>

app-controls contains buttons that need to trigger events in the app-main component. Is there a Angular 2 style guide compliant way of doing so?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a template variable to get a reference to the sibling. If <app-controls> has an output where it emits events when a button is clicked you can do:

<app-controls (buttonClicked)="main.doSomething($event)"></app-controls>
<app-main #main></app-main>

or you can pass a reference to a @Input() siblings; and then call methods on it:

<app-controls [sibling]="main"></app-controls>
<app-main #main></app-main>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...