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

angular - Calling a function in a child Angular2 Component?

I have a Component that acts as a Search Bar. It can make api requests and provide the results to the rest of the app through an @Output and EventEmitter but I also want a function to go the other way. The Search Bar component keeps a history of it's searches and I would like to provide a way for the parent component to clear the history. The best I can think of is to somehow call a method in my Search Bar from a parent component.

The best I've come up with (but haven't been able to properly implement) is to try to pass an EventEmitter INTO my Search Bar and the child subscribes to the parent's events. The @Input hasn't completed binding by the time the constructor though so it gets tricky to actually do this.

I suppose I could try and store the history in the parent component, but the reason the Search Bar is a component is because it will appear in multiple places and this doesn't fit with Separation of Concerns so it seems best to keep the history in the Search Bar component.

How can a parent Component call a function on a child Component?

question from:https://stackoverflow.com/questions/35140674/calling-a-function-in-a-child-angular2-component

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

1 Answer

0 votes
by (71.8m points)

It turns out I can put a local variable on the component and have access to it's public functions. I.e.:

<search-bar #SearchBar ...></search-bar>
<button (click)='SearchBar.ClearHistory()' ...></button>

Apparently the local variable binds to the Component and not the DOM like I originally thought it did. I imagine that I have access to all public fields and functions.


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

...