How to trigger a component programmatically in Angular 6

Whenever I hover over an <li> tag, I want to trigger a function that will execute a detailed component.

  findId(id:number){
     console.log(id)
  }

While this function is executing, it should send the id to the following component:

export class DetailComponent implements OnInit {

    @Input() id:number;
    constructor() { }
   ngOnInit() {
   }
  }

Here is the corresponding HTML code:

<ul>
  <li *ngFor="let cat of cats" >
    <a (mouseover)="findId(cat.id)">{{cat.name}}</a>
  </li>
</ul>

Check out a live demo of my code

Any ideas on how to achieve this?

Answer №1

I found valuable information for my response in the official documentation. Checking out this link would be beneficial.

There are various scenarios to consider, so let's explore them:

  • If DetailComponent is the child of your current component
  • If DetailComponent is the sibling of your current component
  • If DetailComponent is the parent of your current component

Situation 1: DetailComponent is the child of your current component

As mentioned by @nguyen in his explanation, if DetailComponent is a child and you have used the @Input decorator, you can pass values like this:

<app-detail[id]="selectedId"></app-detail>

Assuming that selectedId is the variable in your current component holding the id you want to send to DetailComponent.

If your function works properly and you see the id in console with:

findId(id:number){
     console.log(id);
     this.selectedId = id;
  }

For Situations 2 and 3, refer to the documentation for passing values using event emitters or consider creating a service to share common values among components.

In your Current Component:

export class CurrentComponent implements OnInit {

    constructor(public dataStoreService: DataStoreService) { }
    ngOnInit() {}

    findId(id:number){
     this.dataStoreService.selectedId = id;
  }
  }

Then in your DetailComponent, import the service as well:

export class DetailComponent implements OnInit {

    constructor(public dataStoreService: DataStoreService) { }
    ngOnInit() {}
  }

In your DetailComponent html template:

<div>{{dataStoreService.selectedId}}</div>

If CurrentComponent and DetailComponent are siblings, they can both use the same shared variable from the service to update or display data collectively.

Answer №2

If the DetailComponent has been specified with the selector app-detail

You must transfer the id from the input to it

<app-detail [id]="transferredId"></app-detail>

and within the component containing the detail component, you should assign the value to transferredId (or any other name you choose)

public transferredId;

public setTransferredId(id:number) {
    this.transferredId = id;
}

I hope this provides clarity

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

Sending a POST request from a React application to a Node server and processing the JSON

I'm a beginner in React and I'm working on understanding how everything comes together. Is there a way to switch the rendering component for another one after receiving a status 200 response from a node server? For instance, if I make a POST re ...

Navigating through JSON object array using *ngFor directive in Angular 4

I am trying to iterate through an array of objects stored in my JSON file. JSON [ { "name": "Mike", "colors": [ {"name": "blue"}, {"name": "white"} ] }, { "name": "Phoebe", "colors": [ {"name": "red"}, { ...

Implementation issue with Hashids library in Vue.js causing functionality hiccups

I'm having trouble getting the library hashids to cooperate with vue.js The method I would like to use is: <template> <div class="container"> {{ hashids.encode('1') }} </div> </template> <script& ...

passport.js and express: TypeError - Router.use() must be given a middleware function, but instead received a ' + gettype(fn)

I encountered an error while using passport.js with Express.js TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) This issue arose from the following code: passport/local.js var LocalStrategy = require("passport ...

Loop through unique IDs using AngularJS ng-repeat

I am just starting to delve into AngukarJS and ionic framework, embarking on the journey of creating an app with a structured tree layout as follows: Home Tab (list of books) (templates/allbooks.html) > unique book (book description and chapters) (tem ...

Leverage the power of Angular's route resolve function

Can anyone assist me with a problem I'm facing? I am looking for a way to delay the display of a view until my data is loaded. After some research, I was thinking of using a resolve in the route, but I can't seem to figure out how to implement it ...

Webpack and incorporating bespoke scripts

Can someone please help me understand how webpack works? I'm currently working on an Angular 2 project with a webpack starter and I have some JavaScript scripts from AWS (my SDK for API Gateway). These are about 10 JS files that I currently have liste ...

The module 'SharedModule' has imported an unexpected value of 'undefined'

When working with an Angular application, I want to be able to use the same component multiple times. The component that needs to be reused is called DynamicFormBuilderComponent, which is part of the DynamicFormModule. Since the application follows a lib ...

Enhancing the appearance of individual cells within an HTML table by applying custom classes

I'm in the process of automating report generation for my organization. Our workflow involves using R to summarize data from Excel, then utilizing Rmarkdown, knitr, and the "htmlTable" package to generate HTML files. Currently, I am implementing CSS ...

When encountering a 404 redirect, CSS and JS files may fail to display

I created a unique error message using .htaccess, incorporating CSS and JS in separate folders. Although it functions properly when accessed directly, integrating these resources into the 404 Error message results in only the HTML text being displayed with ...

Display the element following a specific component while looping through an array in Vue.js

Currently, I am facing an issue while using a for-loop on the component element. My goal is to display a <p> element next to the <component> element during the loop's third iteration. The challenge lies in accessing the iteration variable ...

Performing operations on information within a map function

While using toLocaleString within this map, I encountered an issue where only one of the payment.amount's returned formatted as currency. {props.paymentDates.map((payment, index) => ( <tr key={"payment-" + index}> <td>{i ...

Display outcomes for chosen checkboxes

When I call the API: $url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/?awb=awbnumber&order=' . $orderrecords[$k]["order_id"] . '&username=admin&password=admin123';, I retrieve the status results of all Order IDs and d ...

Is there a way to create a function in JavaScript that eliminates duplicate Objects within an Array of Objects?

Currently, I'm working on a function to store details of a couch in a JS object with 3 properties locally. The properties include: An ID (obtained from the product URL using a function) A color (retrieved through an event listener) A quantity ...

Display previous messages in React JS chat when scrolling upwards

I am currently working on a chat application, as depicted in the image. Once the chat is initiated, it automatically scrolls down to display the most recent messages. My goal is to implement a feature where when a user scrolls up to reach the oldest mess ...

Adding a structure to a sub-component within Angular 6 by inserting a template

Given the constraints of this scenario, the app-child component cannot be altered directly, leaving us with only the option to interact with the app-parent component. Is there a method available that allows us to inject the template into app-child, such as ...

Triggering a modal window with unique content by clicking on various images

Is there a way to trigger a modal window through clicking on an image? Additionally, can different images open different content upon clicking? I am planning to showcase a portfolio where clicking on an image will activate a modal that displays other image ...

Can angular and grunt support multiple run blocks simultaneously?

Currently, I am configuring $httpBackend to simulate fake API routes while our team of API developers is building them out. However, I am facing an issue where I have to place all the $httpBackend configurations within my run block. This leads to a situa ...

Refreshing Form after Saving in Angular 4

After clicking the Save button, I want to reset the form (addUserForm). I created a modal with a form to input user data. This form serves for both editing existing data and creating new data, with the flag 'Create' or 'Update' differen ...

What causes React component state initialization to return a `never` type when set to null?

Initializing a component's state to null outside of the constructor results in the state having the type never in the render function. However, when the state is initialized within the constructor, the correct type is maintained. Despite many StackO ...