Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k 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 Reply

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.7k users

...