首页 文章

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

提问于
浏览
0

嗨,我尝试传递从其中一个选项中选择的值 . 我使用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 . COMPONENT2

value1: string; //how to pass selected_dog value to component2's value1.

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

我提前感谢您的帮助 .

2 回答

  • 1

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

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

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

  • 0

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

相关问题