MexicoBoy
MexicoBoy

Reputation: 47

How to call value from a class to another in angular

I'm trying to import variables which are from Items class, but I can't figure out how it should be done. Heres an example of my code,

item.ts:

export class Item{
   itemName: string;
   id: sstring;
}

user.ts

import {Item} from './item'

export class Users{
   username: string;
   id: string;
}

The question is how can I get the value itemName inside the user.ts.

Upvotes: 0

Views: 883

Answers (2)

FedG
FedG

Reputation: 1301

The question is not much clear, if you intend not like component.

import {Item} from './item';

 export class User {
      username:string;
      id: string;
      item: Item;
}

In this way you have in User objects of Item type.

Otherwise if Item and User are components, then depends by their relationship. If they are child-parent relation you can use @Input to pass value: In the Item HTML

<user-selector [itemName] = 'item'></user_selector>

in User ts;

@Input itemName: string;

If they are not relation between them, so you can use a service and use Subject to comunicate between them: How can i capture an event in a component which is emitted from another component?

Upvotes: 0

Sam
Sam

Reputation: 1861

These look a lot like models. So you are defining the structure of what a user and item should look like with some typing restrictions. You could add an item to a user's model like so.

import {Item} from './item'

export class Users{
   username: string;
   id: string;
   item: Item;
}

This will type Users.item to your Item class. Just to clarify you would therefore have itemName under user.item.itemName

Upvotes: 1

Related Questions