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

Angular 4 - Execute function from outside of component

I will appreciate your suggestions for the following case: I have a registration component. Our product manager decided to add this registration component to another page. In this page, another button (outside of the registration component) should execute the registration (along with some other logic) I don't want the new page will have to handle the registration code, and it will be great if I can still have all the logic in the registration component. What should I do?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Two ways:

  1. Put the function in a shared service and execute from there
  2. Get the component object and call the function from there:

Lets say your component name is "TestComponent", then:

Add a selector id #test to your selector in test.component.html

<test #test></test>

Get the TestComponent in your the component where you want to call the function:

@ViewChild('test')
private testComponent: TestComponent; 
/* Remember to import the TestComponent in the file where you get this */

Call the method you want to execute. The method must be public in your TestComponent. E.g.

this.testComponent.registerUser();


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

...