【问题标题】:Pass data between two independent components在两个独立组件之间传递数据
【发布时间】:2017-05-16 17:03:02
【问题描述】:

我想在两个独立组件之间传递数据。

例如:

  1. 我有第一个带有输入文本和提交按钮的组件。第二个带输入框的组件
  2. 当用户在第一个组件的文本框中输入数据并单击提交时,他将被路由到第二个组件,在第一个组件的输入文本框中输入的数据应该进入第二个组件的文本框。
  3. 我尝试使用 @Input 和 @Output 但这是用于父子层次结构。
  4. 在我的例子中,我有 2 个独立的组件,其中用户从一个页面到另一个页面的路由是整个视图更改
  5. 我听说要使用服务,但无法在线找到合适的示例或文档。

【问题讨论】:

标签: angular angular-cli


【解决方案1】:

你可以做一个普通的服务,我把它命名为 store。例如,您可以创建一个表单存储forms.store.ts。这家商店将是一项服务

@Injectable()
export class FormsStore {
  inputText : string = '';
  constructor(){
       //Code here
  }
  //Other Functions 
}

在 form.component.ts 中:

 @Component({
    selector: 'form',
    encapsulation: ViewEncapsulation.None,
    template: require('./form.component.html')
})

export class FormComponent{

  constructor(private store: FormsStore) {
  }

  onFormSubmit(value){
   this.store.inputText = value;
  }

}

在 form.component.html 中:

<input (keydown.enter)="onFormSubmit(input.value)" #input>

现在在其他组件中,您可以再次创建 store 的实例并将 'inputText' 值引用为 store.inputText 并使用它。

【讨论】:

    猜你喜欢
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    相关资源
    最近更新 更多