【问题标题】:Angular2 How to pass selected value to other componentAngular2如何将选定的值传递给其他组件
【发布时间】:2017-08-23 18:16:13
【问题描述】:

您好,我正在尝试传递从其中一个选项中选择的值。 我使用 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?)

提前感谢您的帮助。

【问题讨论】:

  • component2是放在component1里面的吗?
  • 不,它们是分开的,这就是为什么我无法使用 EventEmitter 实现我想要的,因为它们与未嵌套的路由相连

标签: angular components eventemitter


【解决方案1】:

在服务中,如果您在获取值方面遇到问题,您可以将变量设为静态并直接访问变量而无需注入,例如 AppMessageService.value1.

【讨论】:

    【解决方案2】:

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

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

    注入上述服务,使用setValue在第1个组件中设置值,在第2个组件中设置getValue。

    【讨论】:

    • 我成功设置了值,但是使用您的代码,getValue 没有打印任何内容。 console.log 是空的(猜测 this.value1=""; 的原因)。我是否需要添加任何其他内容才能将数据从 setValue 传递到 getValue 方法?
    • 调试,看看值是否被设置和检索
    • 会不会是因为调用了ngOnInit方法?
    • 您看到设置的值了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2020-12-30
    • 2018-04-13
    • 2018-07-11
    • 2019-04-03
    • 1970-01-01
    相关资源
    最近更新 更多