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

Creating a personalized attribute directive within Angular2

I've been attempting to apply a custom attribute directive to an input element, but I'm struggling to achieve it. Here is my directive code: @Directive({ selector: '[disable-paste]' }) export class DisablePaste { constructor(p ...

Error: global not declared in the context of web3

I've been attempting to integrate Web3 into my Ionic v4 project for some time now. However, I keep encountering errors when I try to serve the project. Specifically, I receive an error message stating that Reference Error: global is not defined. Cre ...

Cypress and Cucumber synergy: Experience automatic page reloads in Cypress with each test scenario in the Describe block

Hey, I'm facing an unusual issue. I have a dialog window with a data-cy attribute added to it. In my cucumber scenarios, I have one like this: Scenario: Users open dialog window When the user clicks on the open dialog button I've written Cypre ...

Using Moment JS to display the days of the upcoming week

I'm in the process of developing a weather application and I need to create code that will display the upcoming week's weather forecast. The only information I have from the server is a "time" entity with a "value" set for next Monday such as "20 ...

A guide on implementing TypeScript with React Native's platform-specific extensions

The issue at hand: In my react native project, I am using a custom hook that has platform-specific code. I need to import this hook based on the platform in use. When I import it as import useWifi from 'hooks/use-wifi.android';, everything works ...

Include the providers after declaring the AppModule

When it comes to Angular 2+, providers are typically registered in the following manner: // Using the @NgModule decorator and its metadata @NgModule({ declarations: [...], imports: [...], providers: [<PROVIDERS GO HERE>], bootstrap: [...] }) ...

generate a fresh array with matching keys

Here is an example array: subjectWithTopics = [ {subjectName:"maths", topicName : "topic1 of maths " }, {subjectName:"maths", topicName : "topic2 of maths " }, {subjectName:"English", topicName : &quo ...

Cordova's FileReader takes precedence over TypeScript's FileReader functionality

I encountered an issue when adding the cordova-plugin-file-transfer plugin, where I received the error message: reader.addEventListener is not a function. This problem arises due to Cordova FileReader class overriding typescript FileReader. How can this ...

Replace the default Material UI 5.0 typography theme with custom fonts on a global scale

My current challenge involves incorporating two personal fonts into the Material UI 5.0. My goal is to apply these fonts globally by overriding the theme settings. However, I have encountered issues with loading the fonts properly and modifying the typogra ...

Top method for converting scrolling into an element

When trying to create a scrollable element, I attempted the following: .scroll-content { overflow: hidden; } .scrollabe { overflow-y: scroll; } <ion-content> <ion-grid style="height:100%" *ngIf="plat && ticket"& ...

"Receiving an error message stating 'Was expecting 1 parameter, received 2' while trying to pass a useState function in TypeScript

I am encountering an issue with a component where I pass a useState setter to a utility function: export interface IData { editable: string[]; favourited: string[]; } const [data, setData] = useState<IData | undefined>(undefined) useEffect(() = ...

When using Vue.js, you may encounter an error message stating that the `document.title` type of 'undefined' cannot be assigned to type 'string' in Typescript

I'm trying to use beforeEnter with Vue Router, but I encountered an error: TS2322: Type 'string | symbol | null | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string&apo ...

When the first argument is missing, using a recursive constraint default can result in the incorrect inference of the second argument, especially when both arguments share the same generic

Currently, I am developing a TypeScript implementation of a recursive binary search tree (BST) data structure using generic constraints. In order to establish a default for the recursive generic variable T without directly using it in the default declarati ...

Can an Angular Component be displayed using a Serverless function like Lambda on AWS?

I have a single-page application developed in JavaScript using the Angular 6 Framework, and I am interested in dynamically rendering an Angular Component that is hosted on a remote server. Currently, I am utilizing viewContainerRef to dynamically render ...

Enhancing TypeScript builtin objects in Netbeans using a custom plugin

While in the process of converting JavaScript code to TypeScript, I encountered a challenge with extending built-in objects using Object.defineProperty, such as String.prototype. Object.defineProperty(String.prototype, 'testFunc', { value: funct ...

When I start the Chrome debugger, my breakpoints do not appear on the screen

Using IDE Visual Studio Code Reviewing tsconfig.json settings: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap": t ...

Delivering static HTML routes in a React App using Typescript

I am working on a React app with functional components, and everything is working perfectly with its own CSS. Now, I have a separate static HTML file (FAQ) with its own CSS and design that I want to incorporate as a new route at /FAQ. I don't want th ...

Tips for maintaining the original data type while passing arguments to subsequent functions?

Is there a way to preserve generic type information when using typeof with functions or classes? For instance, in the code snippet below, variables exampleNumber and exampleString are of type Example<unknown>. How can I make them have types Example& ...

Encountering Issues with TypeScript Strict in Visual Studio Code Problems Panel

I have discovered that I can optimize my TypeScript compilation process by utilizing the --strict flag, which enhances type checking and more. Typically, I compile my TypeScript code directly from Visual Studio Code with a specific task that displays the c ...

Angular/Karma Unit Test for HttpClient

During my research on unit testing, I came across some very useful examples. Most of the examples focus on unit testing functions that interact with Angular's HttpClient, and they usually look like this: it('should return an Observable<User[] ...