Angular2如何将选定的值传递给其他组件 [英] Angular2 How to pass selected value to other component
问题描述
我正在尝试传递从选项之一中选择的值。
我使用了ngModel来保存值,但我不知道如何将其传递给其他组件。由于它们是连接的但不是嵌套的,因此我无法使用Eventemitter,因为我认为使用Eventemiiter,因此我应该使用子组件的选择器将组件嵌套在父组件中,而我不想这样做。
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?
下面是我的代码。
组件1的模板
<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的组件
Component1's component
selected_dog: string;
printValue () {
console.log (this.selected_dog)} // checked if the value is properly stored.
现在,我想将 selected_dog值传递给Component2。
Component2
And now, I want to pass 'selected_dog' value to Component2. Component2
value1: string; //how to pass selected_dog value to component2's value1.
我不确定要使用什么(eventEmitter,输出/输入?/ ng含量?)
I am not sure what to use ( eventEmitter, output/ input? / ng-content?)
感谢您的帮助。
推荐答案
我建议您创建一个服务并存储变量值,在这两个组件之间使用变量。
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;
}
注入上述服务,并使用setValue设置第一个组件中的值和getValue在第二部分中。
Inject the above service and use setValue to set the value in 1st component and getValue in the 2nd component.
这篇关于Angular2如何将选定的值传递给其他组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!