Angular2如何将选定值传递给其他组件

时间:2017-03-30 02:24:13

标签: angular components eventemitter

您好我尝试传递从其中一个选项中选择的值。 我使用ngModel来保存值,但我无法弄清楚如何将它传递给其他组件。由于它们是连接但没有嵌套,我无法使用Eventemitter因为我认为使用Eventemiiter,我应该使用子组件的选择器将组件嵌套在父组件中,我不想这样做。

这两个组件是分开的,我想将选定的值传递给另一个组件?我怎样才能做到这一点?

以下是我的代码。

组件1的模板

b

Component1的组件

 <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>

现在,我想将'selected_dog'值传递给Component2。 Component2

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

我不确定要使用什么(eventEmitter,输出/输入?/ ng-content?)

我提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

我建议你创建一个服务并存储变量值,在这两个组件中使用变量。

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

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

getValue() {
 return this.value1;
}

注入上述服务并使用setValue设置第一个组件中的值和第二个组件中的getValue。

答案 1 :(得分:0)

在服务中,如果您遇到get value问题,可以将变量设置为static,只需访问变量,甚至无需注入,例如 AppMessageService.value1。

相关问题