How to pass a variable from component to component effectively in Angular 14

Viewed 64

I have a two component. One of them is the main page and other one is a pop-up component. There is a variable in my main page and I want to pass that variable to pop-up. How can I do it without importing the whole main page to pop-up?

I tried to do the method right below but couldn't make it work

constructor(
    private service:InvestService,
    private investId:MainPageComponent["investId"]) { }

I got the warning below from my IDE but I couldn't make sense of it.

No suitable injection token for parameter 'investId' of class 'MainPageComponent'.
  Consider using the @Inject decorator to specify an injection token.

Can you help me out please?

1 Answers

You can have the pop up component as a child in your main page and use the input decorator, you can check the documentation here https://angular.io/guide/inputs-outputs, but here is an example:

(Parent) Main Page Component:ts file

fruits: string[] = ['apple', 'banana', 'mango'];

html file

<h1>List of fruits</h1>
<app-popup [fruits]="fruits"></app-popup>

(Child) PopUp Component: ts file

@Input() fruits: string[]; 

Now you have a variable called fruits with the values passed from the parent

Related