Call child component method from parent class - Angular
I think most easy way is using Subject. In below example code, the child will be notified each time 'tellChild()' is called.
Parent.component.ts
import {Subject} from 'rxjs/Subject';
...
export class ParentComp {
changingValue: Subject<boolean> = new Subject();
tellChild() {
this.changingValue.next(true);
}
}
Parent.component.html
<my-comp [changing]="changingValue"></my-comp>
Child.component.ts
...
export class ChildComp implements OnInit{
@Input() changing: Subject<boolean>;
ngOnInit(){
this.changing.subscribe(v => {
console.log('value is changing', v);
});
}
}
Working sample on Stackblitz
You can do this by using @ViewChild
for more info check this link
With type selector
child component
@Component({
selector: 'child-cmp',
template: '<p>child</p>'
})
class ChildCmp {
doSomething() {}
}
parent component
@Component({
selector: 'some-cmp',
template: '<child-cmp></child-cmp>',
directives: [ChildCmp]
})
class SomeCmp {
@ViewChild(ChildCmp) child:ChildCmp;
ngAfterViewInit() {
// child is set
this.child.doSomething();
}
}
With string selector
child component
@Component({
selector: 'child-cmp',
template: '<p>child</p>'
})
class ChildCmp {
doSomething() {}
}
parent component
@Component({
selector: 'some-cmp',
template: '<child-cmp #child></child-cmp>',
directives: [ChildCmp]
})
class SomeCmp {
@ViewChild('child') child:ChildCmp;
ngAfterViewInit() {
// child is set
this.child.doSomething();
}
}