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

Is Q.js capable of functioning independently from node.js and require()?

Currently experimenting with the latest version of q.js to integrate promises into my ajax calls without utilizing node.js at all. I retrieved the most recent version from https://github.com/kriskowal/q and only included q.js in my project. While testing, ...

Troubleshooting multiple element visibility problems with jQuery

Please take a look at the code snippet below. $(document).ready(function(){ $(".like-btn").hover(function() { var rowid = $(this).attr("data-rowid"); $(".reaction-box[data-rowid='" + rowid + "']").fadeIn(100, function() { $(".reaction ...

The last javascript file that was included has been overlooked

When using jqplot, I noticed that the last included plugin is being ignored. If I switch their positions, the first to last one works while the last one does not. There are no errors in the console to indicate what might be going wrong. Moving the canvasOv ...

Hey there, I'm looking to use different CSS fonts on Windows and Mac for the same page on a web application. Can someone please guide me on how to accomplish this?

In order to tailor the font based on the operating system, the following criteria should be followed: For Windows: "Segoe UI" For Mac: "SF Pro" Attempts have been made using the code provided below, but it seems to load before the DOM and lacks persisten ...

The program encountered an error while trying to access the undefined property '_header'

An issue arises when the app.use(express.static("web")) line is executed. var express = require('express')(); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); //app.get(&apo ...

Image displaying recreation of drop down lists similar to those found on Facebook pop-up windows

Seeking guidance on how to create popup drop-down lists similar to Facebook's "Who liked this link?" feature. I believe it involves the use of jQuery. Click here for an example image. Any suggestions, folks? ...

Enhance the overall appearance of select elements across all components using Material UI's

I'm attempting to change the border color of my outlined select elements using the code below, but it's not working as expected. It seems that the border style is being inherited from the fieldset element. I've experimented with using MuiOut ...

Complete the dynamic form submission in a non-blocking manner

My goal is to dynamically add text fields with the click of a button I also aim to extract data from these text fields and insert it into the database Currently, all functions work smoothly, I just need this additional feature. Per ...

I'm wondering why my .focus() function is causing the cursor to move to the start of my contenteditable div?

I am currently developing a website for writing books, primarily using php. I have implemented a jQuery function that, upon clicking the "New Chapter" button, triggers an AJAX function along with various other JS/jQuery events. One of these events is inten ...

Defining types for functions that retrieve values with a specified default

My method aims to fetch a value asynchronously and return it, providing a default value if the value does not exist. async get(key: string, def_value?: any): Promise<any> { const v = await redisInstance.get(key); return v ? v : def_value; } W ...

What is the process for including default components in Angular CLI version 6 and above?

The former angular cli had a key called defaults: "defaults": { "schematics": { "collection": "@nrwl/schematics", "postGenerate": "npm run format", "newProject": [ "app", "lib" ] }, "styleExt": "scss", ...

Implementing SAML Authentication in Angular and .NET WebAPI

I am in the process of setting up a website that utilizes Angular for the user interface, .NET for the backend APIs, and integrates SAML for authentication with a third-party Azure AD. I'm finding it challenging to grasp how each component interacts w ...

Sequence of background colors not altering as intended

After clicking a button, I included the following jQuery code in a code snippet on my WordPress site: jQuery("#cf_course_planner tr").css("background-color", "#f66"); jQuery("#cf_course_planner tr:eq(0)").css(& ...

Troubleshoot: React and Laravel login authentication issues

I am relatively new to working with React, React Router, and Laravel for authentication. I've been trying to set up authentication using Laravel, React, and React Router, and although the page redirects to the desired destination when the submit butto ...

"Concealing tooltip boxes in Vue: A step-by-step guide

I am trying to achieve a functionality where a tooltip box appears on each incorrect or empty input field when the 'Save' button is pressed. I have been able to display the tooltip boxes upon clicking the 'Save' button, but the issue ar ...

`Heart-shaped loading bar in Reactjs`

Looking for help in creating a heart-shaped progress loader for a React project. I attempted using CSS but encountered issues with the progress not filling the entire heart design. Below is the code snippet I used. The progress should start from the bottom ...

Turning On/Off Input According to Selection (Using jQuery)

<select name="region" class="selection" id="region"> <option value="choice">Choice</option> <option value="another">Another</option> </select> <input type="text" name="territory" class="textfield" id="territo ...

Utilizing Arrow Functions with Parameters in Angular

I am currently working on an Angular 4 app and I am attempting to create a queue of actions. Each action should only be executed after the previous one has finished, and each action should receive its own set of parameters. public activeRegistrationAndS ...

What is a way to activate the onSelectionChange event only when the cursor moves without any changes in the input?

In my React Native app, I have a use case where I want to implement mentions. This requires calling a function on the onSelectionChange event only when the text in the input remains unchanged but the caret position has moved. Currently, the onSelectionCha ...

Issue encountered while serializing data in next.js when utilizing getServerSideProps function

Encountering An Error Error: The error message "Error serializing .myBlogs returned from getServerSideProps in "/blog"" keeps popping up. I'm facing a problem while attempting to log the data! Initially, when I was fetching data using use ...