Skip to content

Instantly share code, notes, and snippets.

@gearmobile
Created September 3, 2020 07:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gearmobile/7f591ad856022746bf92582cff9fddb2 to your computer and use it in GitHub Desktop.
Save gearmobile/7f591ad856022746bf92582cff9fddb2 to your computer and use it in GitHub Desktop.
Angular - Call child component method from parent
<button (click)="callChild()"> Call child </button>
<button (click)="childcomp.sayHello()"> Call child from view</button>
<app-comp-a #childcomp ></app-comp-a>
import { Component, OnInit, ViewChild } from '@angular/core';
import { CompAComponent } from './components/comp-a/comp-a.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'angular-learning';
@ViewChild(CompAComponent) childcomp: CompAComponent;
ngOnInit(): void { }
callChild() {
this.childcomp.sayHello()
}
}
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-comp-a',
templateUrl: './comp-a.component.html',
styleUrls: ['./comp-a.component.scss']
})
export class CompAComponent implements OnInit {
constructor() { }
ngOnInit() { }
sayHello(){
alert("Hello from comp-a");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment