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.5k views
in Technique[技术] by (71.8m points)

angular - How to call router outlet child component method from parent comonent

I am new to angular2

<parent>
    <router-outlet><router-outlet>
</parent>

I have a button in parent component, if I click that button it should call a method in the child component (which is loaded in router outlet.)

Is there any way to call the child component (in router outlet) method from parent ?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There are basically two ways to display a component's template: As a nested component or as a routing target.

Nested Component

If you use a nested component, then the components are considered to have a "parent component/child component" relationship.

The Html for the parent component would then look like this:

<div>
   <child></child>
</div>

Where "child" is the selector of the child component. You can then communicate between the two using @Input and @Output properties.

For more information on this technique when you have nested components, check out the docs here: https://angular.io/guide/component-interaction

Routing Target

If you use a component as a routing target by displaying it in a <router-outlet>, then there is no "parent component" and "child component" relationship.

The best way to communicate between components in this case is to use a service.

I have a blog post about creating a service here: https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/

Resources

If you are new to Angular, you may save your self a bunch of time and frustration by working through a tutorial or online course. That will introduce all of the basic concepts to get you on your way with Angular quickly.

You can work through the "Tour of Heroes" tutorial here: https://angular.io/tutorial

Or watch a course such as this one: https://app.pluralsight.com/library/courses/angular-2-getting-started-update

Or this one: https://app.pluralsight.com/library/courses/angular-2-first-look/table-of-contents

(You can sign up for a free week.)


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

...