Categories
Angular Answers

How to call a method in the child component with Angular?

Spread the love

Sometimes, we want to call a method in the child component with Angular.

In this article, we’ll look at how to call a method in the child component with Angular.

How to call a method in the child component with Angular?

To call a method in the child component with Angular, we can use ViewChild.

For instance, we write

@Component({
  // ...
})
export class Parent {
  @ViewChild(Child) child: Child;

  incrementSonBy5() {
    this.child.updateData(this.child.data + 5);
  }
}

to create the Parent component.

We reference the Child component with @ViewChild(Child) child: Child;.

Then we get the properties and methods in Child with this.child.

Next, we add the Child component with

@Component({
  // ...
  template: `{{ data }}`,
  // ...
})
export class Child {
  data: number = 3;

  constructor() {}

  updateData(data: number) {
    this.data = data;
  }
}

We add the data property and the updateData component method that were referenced in Parent.

Conclusion

To call a method in the child component with Angular, we can use ViewChild.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *