What is the best way to connect Classes and Objects in Angular5?

Picture a study tool with flashcards and different categories. Each category has a title, while each card contains content, is linked to only one category, and is also connected to another card.

How can I establish these connections in Angular 5 and Typescript without relying on external services? By connections, I mean how can the class independently determine its associated elements?

/* card.ts */
export class Card {
  public id: String;
  public content: String;
  public link: Card;
  public category: Category;

  constructor(
    content, category
  ) {
    this.content = content;
    this.category = category;
    this.generateId();
  }

  private generateId(): void {
    this.id = /* generate unique id */;
  }

  public setLink(card) {
    this.link = card;
  }
}

/* category.ts */
import { Card } from './card';    

export class Category {
  public title: String;
  public slug: String;

  constructor (
    title
  ) {
    this.title = title;
    this.generateSlug();
    this.generateId();
  }

  private generateId(): void {
    this.id = /* generate unique id */;
  }

  public getCards: Card[] {
    /* I NEED ASSISTANCE HERE */
    /* perform magic to retrieve all cards related to this category */
  }
}

I have indicated within the code (I NEED ASSISTANCE HERE) the point where a category should be able to identify all corresponding cards within that specific category. In the future, I aim to simply call Category.getCards() to access all cards linked to the chosen category.

Previously, I attempted to create service providers to scan through all cards and locate the appropriate ones, but I encountered difficulties injecting these services into my class for utilization.

PS: My background lies in PHP and Laravel, which provides seamless connections between classes using various relationships.

Answer №1

To start, you must determine the method by which your category will access the cards. Essentially, you want to iterate through the cards array and extract the items that match the specific category.

Here is a potential solution:

public retrieveCards(): Card[] {
  return cards.filter(card => card.category === this);
}

The main question now is how the category will have access to the cards array. You can either pass it as an argument to retrieveCards(), include it in a category constructor, or if it's a global variable, simply import it. The choice is yours on how to proceed.

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

Passing along the mouse event to the containing canvas element that utilizes chart.js

Recently, I created a custom tooltip for my chart.js chart by implementing a div that moves above the chart. While it works well, I noticed that the tooltip is capturing mouse events rather than propagating them to the parent element (the chart) for updati ...

Is there a way to fetch a particular object from Firebase database based on its value using AngularFire2?

Here is the database I am working with: firebase database I am trying to retrieve a dish that has its 'featured' attribute set to true (dish.feature = true). Is it possible to do this directly from the database, or do I have to retrieve all di ...

Ways to sort through a Unix timestamp

Recently, I encountered an issue with my Ionic mobile application. It has a search button and filter feature that works well for filtering words. However, the problem arises when it comes to filtering dates displayed in the app as timestamps using Angular ...

After upgrading from angular version 7.0 to 8.0, I realized that the target in the tsconfig.json file remained unchanged

After running the command ng update @angular/cli @angular/core, I successfully updated my Angular 8 version. The updated versions are as follows: Angular CLI: 8.0.1 Node: 10.15.3 OS: linux x64 Angular: 8.0.0 ... animations, cdk, common, compiler, compiler ...

Observable function encountering difficulties returning nested values

I've been working on a function that returns an observable. test(id: int): Observable<Group>{ this.http.get('test/').subscribe( (result:any) => { resultingVal = Group.fromJson(result.group); }); } Right now, the function ...

When using React MUI Autocomplete, make sure to handle the error that occurs when trying to filter options using the

I am trying to implement an autocomplete search bar that makes a custom call to the backend to search through a list of tickers. <Autocomplete multiple id="checkboxes-tags-demo" options={watchlis ...

What is the technique for highlighting the exact data point on the XY am4chart when it is clicked?

I have been searching high and low for a solution to my problem but haven't had any luck. I am working with a traditional XY am4chart that has hundreds of data points in the line series. What I want is for the chart to display a vertical line (or some ...

Generating a collection of objects using arrays of deeply nested objects

I am currently working on generating an array of objects from another array of objects that have nested arrays. The goal is to substitute the nested arrays with the key name followed by a dot. For instance: const data = [ id: 5, name: "Something" ...

`How can I eliminate all duplicate entries from an array of objects in Angular?`

arr = new Array(); arr.push({place:"1",name:"true"}); arr.push({place:"1",name:"false"}); arr.push({place:"2",name:"false"}); arr.push({place:"2",name:"false"}); arr.push({place:"3",name:"false"}); arr.push({place:"3",name:"true"}); I'm curious about ...

Implementing a persistent "remember me" feature in Angular 2 without relying on local

Is it possible to implement a "remember me" feature in Angular 2 without relying on the use of local storage? ...

Strategies for packaging and integrating dependencies within Angular-CLI libraries

I am encountering difficulties with bundling dependencies in my project. The library package I have created serves as a wrapper for @angular/material components. To my surprise, each time I install my library package, the installation process also prompt ...

Angular 6 Error: Failed to parse template. Unable to establish a connection with 'routerLink' as it is not recognized as a valid property of 'a'

During app testing with npm test An error is encountered : Failed: Template parse errors: Can't bind to 'routerLink' since it isn't a known property of 'a'. (" <nav> <ul> <li><a class=" ...

The Application Insights Javascript trackException function is giving an error message that states: "Method Failed: 'Unknown'"

I've been testing out AppInsights and implementing the code below: (Encountering a 500 error on fetch) private callMethod(): void { this._callMethodInternal(); } private async _callMethodInternal(): Promise<void> { try { await fetch("h ...

Limit Typescript decorator usage to functions that return either void or Promise<void>

I've been working on developing a decorator that is specifically designed for methods of type void or Promise<void>. class TestClass { // compiles successfully @Example() test() {} // should compile, but doesn't @Example() asyn ...

Encountering error code TS1003 while trying to access object properties using bracket notation in Typescript

How can object property be referenced using bracket notation in TypeScript? In traditional JavaScript, it can be done like this: getValue(object, key) { return object[key]; } By calling getValue({someKey: 1}, "someKey"), the function will return 1. H ...

Exploring ways to conduct a thorough scan of object values, inclusive of nested arrays

My goal is to extract all values from an object. This object also includes arrays, and those arrays contain objects that in turn can have arrays. function iterate(obj) { Object.keys(obj).forEach(key => { console.log(`key: ${key}, value: ${o ...

Error message in CodeSandBox with Angular: TypeError - The function html2canvas_1.default is not defined or recognized

Attempting to convert a basic html table into a PDF format within my project has resulted in unexpected errors when using CodeSandbox: ERROR TypeError: html2canvas_1.default is not a function at AppComponent.downloadPDF (https://3d3bh.csb.app/src/app/a ...

What benefits do Definitely Typed TypeScript files offer for Knockout and jQuery?

I'm not sure if this is a silly question, but I was wondering if it's necessary to use definitely typed (.d.ts) versions of external libraries when working with Typescript. Currently, my code base uses jQuery and Knockout in the traditional manne ...

How can one access a specific element by its id that is located within an ng-template in Angular 6?

I have a question regarding accessing a button element inside an ng-template tag using its id in the TypeScript file. How can I accomplish that without encountering undefined errors? This is what I have tried so far: HTML <ng-template #popup > ...

Running Swagger within an Angular 5 environment - a step-by-step guide!

How do I integrate Swagger into my UI? Here's what I tried: import * as SwaggerUI from 'swagger-ui'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.c ...