Angular2 如何将选定的值传递给其他组件
Angular2 How to pass selected value to other component
您好,我正在尝试传递从其中一个选项中选择的值。
我使用 ngModel 来保存值,但我不知道如何将它传递给其他组件。因为它们是连接的但没有嵌套,所以我不能使用 Eventemitter,因为我认为使用 Eventemiiter,我应该使用子组件的选择器将组件嵌套在我不想做的父组件中。
这两个组件是分开的,我想将选定的值传递给另一个组件?我怎样才能做到这一点?
下面是我的代码。
组件 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 的组件
selected_dog: string;
printValue () {
console.log (this.selected_dog)} // checked if the value is properly stored.
现在,我想将 'selected_dog' 值传递给 Component2。
组件 2
value1: string; //how to pass selected_dog value to component2's value1.
我不确定要使用什么(eventEmitter、输出/输入?/ng-content?)
在此先感谢您的帮助。
我建议您创建一个服务并存储变量值,在这两个组件中使用该变量。
@Injectable()
export class AppMessageService {
value1: string;
constructor() {
this.value1="";
}
}
setValue(data: string) {
this.value1= data;
}
getValue() {
return this.value1;
}
注入上述服务并使用 setValue 在第一个组件中设置值,在第二个组件中使用 getValue。
在服务中,如果您遇到获取值的问题,您可以将变量设置为静态变量,甚至无需注入即可访问该变量,例如
AppMessageService.value1.
您好,我正在尝试传递从其中一个选项中选择的值。 我使用 ngModel 来保存值,但我不知道如何将它传递给其他组件。因为它们是连接的但没有嵌套,所以我不能使用 Eventemitter,因为我认为使用 Eventemiiter,我应该使用子组件的选择器将组件嵌套在我不想做的父组件中。
这两个组件是分开的,我想将选定的值传递给另一个组件?我怎样才能做到这一点?
下面是我的代码。
组件 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 的组件
selected_dog: string;
printValue () {
console.log (this.selected_dog)} // checked if the value is properly stored.
现在,我想将 'selected_dog' 值传递给 Component2。 组件 2
value1: string; //how to pass selected_dog value to component2's value1.
我不确定要使用什么(eventEmitter、输出/输入?/ng-content?)
在此先感谢您的帮助。
我建议您创建一个服务并存储变量值,在这两个组件中使用该变量。
@Injectable()
export class AppMessageService {
value1: string;
constructor() {
this.value1="";
}
}
setValue(data: string) {
this.value1= data;
}
getValue() {
return this.value1;
}
注入上述服务并使用 setValue 在第一个组件中设置值,在第二个组件中使用 getValue。
在服务中,如果您遇到获取值的问题,您可以将变量设置为静态变量,甚至无需注入即可访问该变量,例如 AppMessageService.value1.