Angular2 How to pass selected value to other component

拟墨画扇 提交于 2019-12-12 02:26:14

问题


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.


回答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.




回答2:


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.



来源:https://stackoverflow.com/questions/43107405/angular2-how-to-pass-selected-value-to-other-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!