2

I have components in hierarhy: app.component > intro.component > header.component. I want to use in header.component, method that is defined in app.component. I recognize there's way to make it with @viewChild. What's easest way to make it work?

//edit I want to do (click) event on html tag that is in header.component.html. In this function I want to run method from app.component.

3
  • You are in right direction. You should use @ViewChild decorator. Commented Sep 26, 2017 at 11:09
  • What do you mean by a method 'initialized' in app.component? Are you asking about how to call a method defined in app.component in header.component or vice versa? Or is it about a 'property' initialized in app.component to be passed to the header.component? Commented Sep 26, 2017 at 11:20
  • I meant that method is defined. U updated post, thanks Commented Sep 26, 2017 at 12:08

2 Answers 2

1

You can also pass callback function to child component as @input (React style):

	//app.component.html:

	<app-intro [appMethod] = "boundMethod"></app-intro>

	export class AppComponent {	

	    ngOnInit() {
                this.boundMethod = this.appMethod.bind(this);
	    }

	    appMethod() {
                console.log("appMethod called");
	    }
	}


	//intro.component:

	<app-header [appMethod] = "appMethod"></app-header>

	export class IntroComponent {
	    @Input() public appMethod: Function; 
	}

	//header.component:

	export class HeaderComponent {
	    @Input() appMethod: Function; 
	    ngOnInit() {
                appMethod(); // Call parent method 
	    }
	}

Sign up to request clarification or add additional context in comments.

Comments

0

A possible example:

In the html in app.component.html:

...<app-intro></app-intro>

the html in intro.compoennt.html:

...<app-header #header></app-header>

and in app.component.ts:

@ContentChild("header")
public headerComponent: HeaderComponent;

Check https://angular.io/api/core/ContentChild

4 Comments

another possible scenario is that you use a service which you can inject into any control to pass around objects.
Why declare @ViewChild("header") private headerComponent: HeaderComponent; in app.component when i want to run method in header.component?
Sorry, yep, that is a problem: you must declare it as public, if you want it to use outside it's control.
Also, I checked, and there is a slight difference between '@ViewChild and '@ContentChild: check it here. If it is not the direct child in the template, you will not see it with '@ViewChild, but '@ContentChild will "scan" the DOM. I updated the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.