Reputation: 1109
I have a master component and many child components in an Angular application. I am rendering the child component using . Something like this.
<body class="nav-md">
<mainComponent></mainComponent>
<router-outlet></router-outlet>
</body>
My main component has a search box and a button. I want to call functions of my child component when I click the button in mainComponent. Any help would be appreciated.
Upvotes: 0
Views: 117
Reputation: 3771
You can use ViewChild in this case.
Example:
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from '../child.component';
@Component({
selector: 'mainComponent',
template: '<search (onSearch)="onSearch($event)"></search><child-component></child-component>',
})
export class MainComopnent{
// ViewChild takes a class type or a reference name string.
// Here we are using the type
@ViewChild(ChildComponent) child: ChildComponent;
onSearch(search: string) {
this.child.say(search);
}
}
@Component({
selector: 'child-component'
})
export class ChildComponent {
say(something: string) {
console.log(something);
}
}
Upvotes: 1