0

Hi I am tryng to pass value selected from one of the options. I used ngModel to save the value but I can't figure out how to pass it to other component. Since they are connected but not nested, I couldn't use Eventemitter cause I reckon to use Eventemiiter, I should use child component's selector to nest the component in the parent component which I do not want to do.

These two components are seperated and I want to pass selected value to the other component? How can I achieve this?

Below is my code.

Component 1's template

 <div>
    <select (change)="printValue()" formControlName="dogName"  
     class="form-control"  
     class="selectionbox"
     [(ngModel)]="selected_dog" required> 

  <option *ngFor="let d of dogs" [ngValue]="d">
     {{d.dogName}}
  </option>
     </select>

Component1's component

     selected_dog: string; 
     printValue () { 
     console.log (this.selected_dog)} // checked if the value is properly stored. 

And now, I want to pass 'selected_dog' value to Component2. Component2

     value1: string; //how to pass selected_dog value to component2's value1. 

I am not sure what to use ( eventEmitter, output/ input? / ng-content?)

I appreciate your help in advance.

Lea
  • 1,245
  • 5
  • 22
  • 31

2 Answers2

1

I would suggest you to create a service and store the variable value, use the variable across those 2 components.

@Injectable()
export class AppMessageService {
    value1: string;
   constructor() { 
     this.value1="";
   }
}

setValue(data: string) {
 this.value1= data;
}

getValue() {
 return this.value1;
}

Inject the above service and use setValue to set the value in 1st component and getValue in the 2nd component.

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

In the service if you are facing issues with get value you could make the variable static and just access the variable without even injecting, like AppMessageService.value1.