Utilize Typescript to Invoke Functions of Different Components in Angular 2

Hello everyone, I am a newcomer to Angular 2 and I'm looking to utilize the value of one component in another component. This will help me populate data based on that particular value.

In my setup, I have three Components - App.Component, Category.Component, and Products.Component.

Just to clarify, App.Component acts as the parent for both Category.Component and Products.Component.

Let's take a look at the Category.Component Code:

@Component({
selector: 'Categories',
template: `<li *ngFor="#category of categories">
                <a class="" href="{{category.Id}}" (click)="getCategoryProducts(category)">{{category.Name}}</a>
           </li>`,
providers :[CategoryService]

})
export class CategoriesComponent {
getData: string;
private categories: CategoryModel[] = [];
private products:ProductModel[] = [];
private productsComponent:ProductsComponent;
constructor(private _categoryService : CategoryService){
    this._categoryService.getCategories()
    .subscribe(
        a=>{
            this.categories = a;
        }
    );
    console.log(this.getData);

}

getCategoryProducts(category:CategoryModel)
{
    this._categoryService.getProducts(category.Id)
    .subscribe(
        a=>{
            this.products = a;
            this.productsComponent.populateProducts(this.products);
        }
    );
}


}

Now, moving on to the Products.Component Code:

@Component({
selector: 'products',
template: `<div class="products-wrapper grid-4 products clearfix loading">
            <div *ngFor="#product of products"  (click)="getProduct(product)" class="product">
                <div class="product-inner" style="background:url({{product.pictureUrl}})">
                    <div class="time-left">
                        <span class="text">Hourly Deal</span>
                        <ul class="countdown clearfix">
                            <li> 
                                <div class="text">
                                    <span class="hours">00</span>
                                </div>
                            </li>

                            <li> 
                                <div class="text">
                                    <span class="minutes">00</span>
                                </div>
                            </li>
                            <li> 
                                <div class="text">
                                    <span class="seconds">00</span>
                                </div>
                            </li>
                        </ul>
                    </div>
                    <span class="discount-tag">{{product.discount}}%</span>

                </div>
            </div>
            </div>`,
            providers :[CategoryService]

})
@Injectable()
export class ProductsComponent {
private product:ProductModel;
private products: ProductModel[] = [];
constructor(private _categoryService : CategoryService)
{
    this._categoryService.getProducts(0)
    .subscribe(
        a=>{
            this.products = a;
        }
    );
}
getProduct(product:ProductModel)
{
    alert(product.productId);
    this.product = product;
}
populateProducts(products: ProductModel[] = [])
{
    this.products = products;
}
 }

The goal is to transfer Products from the getCategoryProducts function in the Category Component to the Product Component for populating the Products. Any assistance would be greatly appreciated. Thank you!

Answer №1

To integrate the product component into the categories component, you can pass an instance of the product component to the categories component:

<categories [productsComponent]="productsComponent"></categories>
<products #productsComponent></products>

Don't forget to include an input for the productsComponent field in the categories component:

@Component({
  (...)
})
export class CategoriesComponent {
  getData: string;
  private categories: CategoryModel[] = [];
  private products:ProductModel[] = [];
  @Input() // <------
  private productsComponent:ProductsComponent;
  (...)
}

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

Concealing the parent view in Angular 2

I need to hide the above parent view. https://i.stack.imgur.com/CZFTn.jpg Here is my code. Upon clicking any of the boxes, the parent should be hidden and the child should appear. <app-navbar></app-navbar> <div class="cont ...

What is the correct way to define the onClick event in a React component?

I have been encountering an issue while trying to implement an onClick event in React using tsx. The flexbox and button are being correctly displayed, but I am facing a problem with the onClick event in vscode. I have tried several ideas from the stack com ...

Alert an Angular 2 component about changes triggered by a service

Currently working with Angular 2 and utilizing an AuthService for authentication. I am at a crossroads on how to effectively inform other components when a user logs in or out. Seeking advice on the best approach for managing this situation. Any insights ...

Enroll a nearby variable "Data" to an Observable belonging to a different Component within an Angular application

Looking to update the HTML view using *ngIf, depending on a local variable that should change based on an observable variable from a shared service. HTML <div class="login-container" *ngIf="!isAuthenticated"> TypeScript code for the same componen ...

Following the build in Angular, it only displays the index.html file and a blank screen

According to the information on Angular's official website, running the "ng build" command should generate files in the dist folder ready for hosting. However, after running this command, the index.html file is empty except for the page title. When yo ...

A Guide to Implementing Schema.virtual in TypeScript

After switching from using schema.virtual in JavaScript to TypeScript, I encountered an error when trying to use it with TypeScript. Below is my code: UserSchema.virtual('fullname').get(function () { return `${this.firstName} ${this.lastName}` ...

An error occurred as the Serverless Function timed out while attempting to load a dynamic route in Next.js version 13

I have a basic Next.js application with the following route structure: /contentA/ - Static - Initial load: 103 kB /contentA/[paramA]/groups - SSG - Initial load: 120 kB /contentB/[paramA]/[paramB]/[paramC] - SSR (client component) - Initial load: 103 kB ...

Executing the cucumberjs + playwright tests after starting the angular app using the ng serve command

Our testing process involves using cucumberjs and playwright. Is it possible to initiate Angular with ng serve (using test configuration) before running our tests, and then close the application once the tests are complete? Similar to configuring a web s ...

NextJS-created calendar does not begin on the correct day

I'm facing an issue with my calendar code where it starts rendering on a Wednesday instead of a Monday. I want to adjust the layout so that it always begins on a Monday by adding some empty boxes at the start of the calendar. Essentially, I need to s ...

The Vue instance seems to be unable to recognize the shims-vue.d.ts file

I encountered an issue with my Vue file. Here is the code snippet: import Vue from 'vue'; import VueRouter from 'vue-router'; export default Vue.extend({ name: 'MyComponentsName', methods: { doRedirect() { this. ...

Multiple occurrences of Angular @HostListener event being triggered

I am currently working on an Ionic 3 application where I have created an "auto-complete" directive. This directive triggers an auto-complete dialog when the element is focused. The implementation of this in the directive looks like this: @HostListener(&ap ...

Activate the field once the input for the other field is completed

I have a form where the last name field is initially disabled. How can I make it so that the last name field becomes enabled only when the first name is inputted? <form> <label for="fname">First name:</label><br> ...

Ensure that selecting one checkbox does not automatically select the entire group of checkboxes

Here is the code I'm using to populate a list of checkboxes. <label class="checkbox-inline" ng-repeat="item in vm.ItemList track by item.id"> <input type="checkbox" name="item_{{item.id}}" ng-value="{{item.id}}" ng-model="vm.selectedItem" /& ...

Angular-oauth2-oidc does not successfully retrieve the access token when using OAuth2 and SSO

Here's an issue I'm facing: I've been attempting to integrate SSO and OAuth2 flow using angular-oauth2-oidc. When testing with POSTMAN and ThunderClient in VS Code, I managed to receive the correct response (the access_token). However, I am ...

Injecting dependencies into an abstract class in typescript using Angular 2

So I have an abstract class that doesn't have a constructor, and my goal is to inject another class into it. Here's the abstract class: import { ErrorHandler } from '../../shared/services/errorHandler.service'; import { Inject } from ...

Altering the properties of a specified element within TestBed using the overrideComponent method

We are implementing TestBed.overrideComponent() to substitute a component with custom behavior. TestBed.overrideComponent(CoolComponent, { set: { template: '<div id="fake-component">i am the fake component</div>', sel ...

Sending a post request to an Express.js API from a different device

I currently have a server running on localhost:3000, with my app.js set up to utilize the angular router. When attempting to access localhost:3000 in my browser (for example: app.use('/', express.static(path.join(__dirname, '/dist/Client&apo ...

Navigating the store in Ionic Angular using Ngrx

Currently, I am in the process of developing an app using Ionic Angular Cordova. My issue lies in trying to display the state of my application, specifically all the objects within it. However, despite my efforts, the objects that I have added cannot be lo ...

Managing properties of classes within callbacks using TypeScript

I am currently working on the following task: class User { name: string; userService: UserService; //service responsible for fetching data from server successCallback(response: any) { this.name = string; } setUser() { ...

Issue with ngStyle not functioning properly with conditional operator

I am currently learning how to use Angular4 ngStyle by going through a tutorial. Here's the code I have been working on: app.component.html <button [ngStyle]="{ 'backgroundColor': canSave ? 'blue': 'gray', ...