Looking for a method to call a child component's function through a click event triggered from the parent component?

How can I trigger a specific function in my child component from a click event in my parent component? Any assistance would be greatly appreciated!

Answer №1

Utilizing @ViewChild can help achieve this:

Using a type selector

@Component({
  selector: 'child-cmp',
  template: '<p>child</p>'
})
class ChildCmp {
  doSomething() {}
}
@Component({
  selector: 'some-cmp',
  template: '<child-cmp></child-cmp>',
  directives: [ChildCmp]
})
class SomeCmp {
  @ViewChild(ChildCmp) child:ChildCmp;
  ngAfterViewInit() {
    // child is initialized
    this.child.doSomething();
  }
}

Using a string selector

@Component({
  selector: 'child-cmp',
  template: '<p>child</p>'
})
class ChildCmp {
  doSomething() {}
}
@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();
  }
}

For further information, check out: Call child component method from parent class - Angular And here: https://angular.io/guide/component-interaction

Answer №2

Exploring Different Techniques for Event-Based Methods

  1. Monitoring Changes with Input
  2. Listening to an Observable
  3. Triggering an Event Emission

1. Monitoring Changes with Input

export class ParentComponent {
    @Output() public counter: number = 100;

    public handleClick() {
        this.counter += 1;
    }
}

export class ChildComponent implements OnChanges {
    @Input() public counter: number;

    public ngOnChanges(changes: SimpleChanges): void {
        const counterProp = nameof<ChildComponent>('counter');
        if (changes[counterProp]) {
            const count: number = changes.counterProp.currentValue as number;
            console.log(`Count is now ${count}`);
        }
    }
}

2. Listening to an Observable

export class ParentComponent {
    private count: number;
    private counter: BehaviorSubject<number>;
    constructor(private counterService: CounterService) {
        this.counter = this.counterService.getCounter().subscribe((count: number) => {
            this.count = count;
        });
    }

    public handleClick() {
        this.counter.next(this.count + 1);
    }
}

export class ChildComponent implements OnInit {
    private count: number;

    constructor(private counterService: CounterService) {
        this.counterService.getCounter().subscribe((count: number) => {
            this.count = count;
        });
    }
}

export class CounterService {
  private counter: BehaviorSubject<number>;

  constructor() {
    this.counter = new BehaviorSubject<number>();
  }

  public getCounter(): BehaviorSubject<number> {
    return this.counter;
  }
}

3. Triggering an Event Emission

export class ParentComponent {
    private count: number = 0;
    constructor(private counterService: CounterService) {
    }

    public handleClick() {
        this.counterService.increaseCount(this.count + 1);
    }
}

export class ChildComponent implements OnInit {
    private count: number;

    constructor(private counterService: CounterService) {
        this.counterService.counter.subscribe((count: number) => {
            this.count = count;
            console.log(`Count is now ${count}`);
        });
    }
}

export class CounterService {
    public counter = new EventEmitter<number>();

    public increaseCount(count: number) {
        this.counter.emit(count);
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to display images when a single element in a list created by ngFor is hovered over in Angular 2

displayStar(val) { this.starDisplayed = true; } <ul class="listboxtickets"> <li class="selectlistticket" *ngFor="let item of ticketList" (mouseover)="displayStar(item.id)" (mouseleave)="hideStars()"> <div class="ticket ...

Tips for effectively importing specific Bootstrap components in Angular without disrupting the package

Issue overview: In my Angular project, I am using Bootstrap v5.2 and aiming to optimize the package size and loading time by selectively importing only the necessary Bootstrap components. However, when attempting to import individual components like butto ...

Updating the value of the chosen drop down option upon selection

I currently have a Material UI dropdown menu implemented in my project. My goal is to use the selected option from the drop down menu for future search functionality. How can I utilize onChange() to store the selected option effectively? At the moment, I ...

Running unit tests using Typescript (excluding AngularJs) can be accomplished by incorporating Jasmine and Webpack

While there is an abundance of resources on how to unit test with Webpack and Jasmine for Angular projects, I am working on a project that utilizes 'plain' TypeScript instead of AngularJs. I have TypeScript classes in my project but do not use c ...

Preventing duplicate arrays from being stored in localStorage by validating them

Is there a way to ensure that when the "add to favorites" button is clicked, its data is stored in localStorage only once? If it already exists in localStorage, clicking for a second time should not have any effect except showing an alert message. I would ...

Tips for accessing other environment variables within the environment.ts file in an Angular project

Currently, I am working on modifying the 'environment.ts' file within an Angular project to include additional properties. The current setup looks like this: export const environment = { production: false, apiUrl: 'http://example.com&ap ...

transmit information to a service using Angular 8

There are 4 multiselect dropdowns, and when I click on an event, I save the data array of objects in the same component. Now, I need to send this data to display it in another component. To achieve this, I am using a service. However, every time I send th ...

The softAssert method is not available when trying to implement soft assertions within a TypeScript-based Protractor framework

Uncaught TypeError: assertion.softAssert is not a function I recently included a package called soft-assert using npm in my project. To install this package, I executed the following command: npm i soft-assert -g --save-dev Incorporated the following co ...

Throw TypeError: The `pipe` property of `ngrx/store` is undefined during testing

Here is the code snippet from my TypeScript file: this.store.pipe(select(subscribe.getRegCategories)).pipe(takeUntil(this.ngUnsubscribe)).subscribe(data => { if (data && data.length) { this.allRegCategories = data; ...

Tips on informing the TS compiler that the value returned by a custom function is not null

There might be a way to make this code work in TypeScript, even though it's currently showing some errors regarding possible undefined values. Take a look at the code snippet: const someArray: foo[] | null | undefined = [...] // TS fail: someArray ...

What is the best way to determine the final letter of a column in a Google Sheet, starting from the first letter and using a set of

My current approach involves generating a single letter, but my code breaks if there is a large amount of data and it exceeds column Z. Here is the working code that will produce a, d: const countData = [1, 2, 3, 4].length; const initialLetter = 'A&a ...

Error TS 2322 - The property 'id' is not present in the object of type '{ id: number'

Just starting out with Angular and TypeScript. I created a model with the same properties but encountered an error and am struggling to find a solution: TS2322: Type '{ id: number; model: string; plate: string; deliveryDate: string; deadline: st ...

Zendesk API integration with Angular is experiencing issues with retrieving data as a result of a CORS restriction

I have been working with the Zendesk API and have encountered a problem. Despite being able to successfully send POST requests (even though the response indicates an error), I am unable to make GET requests using my Angular 4 application along with HttpCli ...

Deactivate user session in LoopBack 4 API

Can anyone provide a clear example of an API endpoint for logging out that allows for deleting the token stored during login instead of relying on the web browser? It seems there is no documentation available on how LoopBack generates a default user when ...

Sharing screen content in Firefox using Angular 6

I am developing an Angular application that requires screen sharing functionality. I am using adapter.js version 6.4.8 and testing it on Firefox Developer 64.0b11 & Firefox 63.0.3. Since browser implementations differ, my main goal is to make the applicati ...

Update the image on a webpage by simply clicking on the current image

Hey there, I'm looking to implement a feature where users can choose an image by clicking on the current image itself. Here's my code snippet. The variable url holds the default image. My goal is to make the current image clickable so that when ...

What is the best way to reorganize Discord channels based on numerical order when interacting with the application?

Whenever someone submits an application for the server, a designated channel is created at the top of the server (view example here). However, responding to these applications in a consistent order has proven challenging due to various factors. Once I resp ...

Display a single unique value in the dropdown menu when there are duplicate options

Hey there, I'm currently working on retrieving printer information based on their location. If I have multiple printers at the same location, I would like to only display that location once in the dropdown menu. I am aware that this can be resolved at ...

What methods can be used to test scss subclasses within an Angular environment?

Exploring different background colors in various environments is a task I want to undertake. The environments include bmw, audi, and vw, with each environment having its own unique background color. Need help writing an Angular test for this? How can I mod ...

Using class-validator in Node.js to validate arrays of objects

My goal is to verify the Alcohol ID and Alcohol Name for emptiness. Below is the format I am working with: { "barId": "string", "barName": "string", "drinksItems": [ { "alcoholId": "string", "alcoholName": "string", "mixerLis ...