Is there a way to execute the function of component2 that is embedded in the HTML display of component 1?

There are 2 components in my application - principal and menu. The menu component includes a JSON object and HTML code where clicking on an element should trigger a function in the principal component. Upon clicking this function, the selected object should display in the principal component. While I understand this can be achieved within a single component, I am simulating a real-world scenario to address a specific issue. Thank you.

Here is how the components are laid out:

<menu></menu>
<principal></principal>

Code for menu.component:

import { Component, Input } from '@angular/core';
@Component({
selector: 'menu',
template: `Select an animal: <br> <button *ngFor="let item of animals" (click)="getAnimal(item);" style="display:block;">{{item.animal}}</button>`,
styles: [`h1 { font-family: Lato; }`]
})
export class MenuComponent {
  animals = [
    {"animal":"cat"},
    {"animal":"dog"},
    {"animal":"horse"}
  ]
  constructor() {}

}

Code for principal.component:

import { Component, Input } from '@angular/core';
@Component({
  selector: 'principal',
  template: `<h1>Selected animal: {{selectedAnimal}}</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class PrincipalComponent {
  selectedAnimal: any;
  constructor() {}
  
  public getAnimal(item) {
    alert(item)
    this.selectedAnimal = item.animal;
  }

}

This code : https://stackblitz.com/edit/angular-paamqn addresses my question. Now, I have one more query. If I try to call <menu> within the principal component in my actual project, how can I make it function? What changes would be necessary? Can I no longer use #principal?

Rather than:

<principal #principal></principal>

I want to include the html code directly in the principal component:

<!-- html of principal.component.html -->
<menu (callPrincipalMethod)="principal.getAnimal($event)"></menu>
<h1>Selected animal: {{selectedAnimal}}</h1>

Answer №1

To establish a connection between components, you can utilize EventEmitter.

<menu (callPrincipalMethod)="principal.getAnimal($event)"></menu>
<principal #principal></principal>

In the menu.component:

import { Component, Input,  Output, EventEmitter } from '@angular/core';
@Component({
selector: 'menu',
template: `Select an animal: <br> <button *ngFor="let item of aAnimals" (click)="getAnimal(item);" style="display:block;">{{item.animal}}</button>`,
styles: [`h1 { font-family: Lato; }`]
})
export class MenuComponent  {
 @Output()
 callPrincipalMethod = new EventEmitter()

 aAnimals=
 [
  {"animal":"cat"},
  {"animal":"dog"},
  {"animal":"horse"}
 ]
 constructor(){}

 getAnimal(item) {
  this.callPrincipalMethod.emit(item)
 }
}

Link to stackblitz: https://stackblitz.com/edit/angular-ko2d58

Update

If the menu component is within the principal component, exclude the principal in principal.getAnimal($event)

<!-- html of principal.component.html -->
<menu (callPrincipalMethod)="getAnimal($event)"></menu>
<h1>selected animal: {{animal}}</h1>

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

Altering the appearance of an Angular component in real-time by applying various CSS style sheets

I'm currently working on implementing a dynamic style-sheet change for a single-page application using Angular. The concept is to offer users the ability to select from various themes through a dedicated menu. Although only two theme variants are show ...

Tips for utilizing callback function in Angular 4

I previously used the Google API to obtain a current address and now I want to incorporate a callback function in this process using Angular 4. How can I go about implementing it? let geocoder = new google.maps.Geocoder(); geocoder.geocode({ &ap ...

How can I resolve the issue of "Errors detected in your package-lock.json" in NGRX?

I encountered some problems while trying to set up my Angular project in an NX workspace with NGRX and running it through Jenkins. After running npm install, I started getting errors. Has anyone else experienced errors like these after executing: nx updat ...

Is there a way to render a component without having to render AppComponent constantly?

I am looking to display two components (AppComponent and UserComponent) without constantly displaying AppComponent. Here's how my code is structured: app.routing.module.ts const routes: Routes = [ { path: '', component: AppComponent ...

Angular 2 has upgraded its Controller functionality by replacing it with Component

I find it a bit challenging to distinguish between Component and Controller. How was the Controller replaced by component in Angular 2? I came across this description of a component: In Angular, a Component is a distinct type of directive that utilizes a s ...

Navigating with Angular: The URL for the home page should be set as http://localhost:4200/

I recently implemented URL routing in my project, but I have encountered an issue. Upon redirecting to the home page, the URL changes to http://localhost:4200/home. However, I would like the URL for the home page to simply be http://localhost:4200/ instea ...

I wonder what the response would be to this particular inquiry

I recently had an angular interview and encountered this question. The interviewer inquired about the meaning of the following code snippet in Angular: code; <app-main [type]="text"></app-main> ...

Changing row colors based on property conditions in Angular 4

Hey there! I'm fairly new to Angular 4 and I've been working on creating a p-dataTable. My goal is to change the color of each row based on the quantity property of my object. Specifically, if the quantity is less than 10, I want the row to be di ...

I am facing the issue of being unable to bind to 'routerlink' because it is not recognized as a known property of 'a', even after I have declared RouterModule in my app.module

Encountering a template parse error when using [routerlink] in an HTML page, despite importing RouterModule. Here's the relevant HTML snippet: <mat-toolbar color="primary"> <h3 [style.color]="white">ADMIN PORTAL</h3> <span cl ...

Creating a list of components for drag and drop with Angular CDK is a straightforward process that involves following

I am attempting to use Angular's CDK drag and drop functionality to create a list of components that can be rearranged. However, I am encountering an issue where the components are not being displayed correctly. In my App.component.ts file: impo ...

Angular application hosted on Apache2 with SSL configured to communicate with a Spring Boot API running on port 8080

After developing a small application using Angular and an API with Spring Boot that includes an embedded Tomcat server, I decided to deploy them on a Raspberry Pi while configuring an SSL certificate with Let's Encrypt. The deployment process involve ...

Passing the value from a custom FormControl component to its parent component

I have successfully implemented a custom form control component with controlValueAccessor and it works well when used directly in a formGroup. Now, I am attempting to use this custom form control component within a "wrapper" component and then utilize the ...

The journey of an Angular and NGXS store application culminates in a seamless loop of store updates

Currently, I am utilizing NGXS as the store mechanism in my application. Within the store, there is a list of conditions that are displayed using the RuleEngineAddViewStepperConditionComponent component and the *ngFor directive on the UI. Each condition ha ...

Issue with ngb-carousel not properly loading upon page refresh within an Angular project

I have integrated ngb-carousel into my Angular application for a basic website. Overall, everything is functioning correctly, but I have noticed that when I refresh the page, the carousel's image takes longer to load compared to the indicators and arr ...

What is the process for creating mandatory fields in Angular?

I'm struggling to set all my fields as required so that when I click the Next button, the form submits and moves on to the next section. I want every field, whether it's a text box, checkbox, select option, or radio button, to be mandatory. ...

Establish a reactive form upon data completion (asynchronously) in Angular version 5

I've been encountering an issue with updating form values post fetching data from an API. I attempted to utilize the *ngIf technique, but unfortunately, the form remains invisible even though it is properly set. Although I cannot provide the entire p ...

implementing the reuse of form control names for multiple dropdowns in an Angular application

When using the dropdown menu, I am facing an issue where selecting a value from the second dropdown makes it disappear. This is because both dropdowns are using the same formControlName to pass values to the backend with the same header. How can this be fi ...

I have been working on building a login page for my node.js project, however, I have been facing challenges with retrieving the stored data from the database

Below is the snippet of code to add a new user into the database const User = require('../database/models/User') module.exports = (req, res) => { User.create(req.body, (error, user) => { if (error) { return res.redi ...

Move the assets folder in Angular to Azure Storage

Looking to streamline my Angular application by transferring all the assets to Azure Storage. Rationale: The assets folder in my repository is cluttered with large, static files that never change. Since we are hosted on Azure, the plan is to move the ass ...

What causes the module declaration in the .d.ts file to fail in an Angular application?

I have recently created a file named global.d.ts within the src folder and it contains the following content: declare module 'ol-contextmenu'; Despite my efforts, placing the file in the root directory or in node-modules/@types did not solve the ...