angular2中多个组件之间的双向数据绑定?

时间:2017-03-15 16:04:40

标签: angular typescript data-binding angular2-components angular2-inputs

我有两个组件HomePageComponent和StudentResultsComponent。我在HomePageComponent中有一个输入,当我输入时,我希望该值在我的StudentResultsComponent输入中。

我想为输入创建一个单独的组件并在两个组件中调用它们,但是当我开始在HomePageComponent中键入时,我的StudentsResultsComponent中的值没有更新。继承我的代码:

Career-Search-Component.html

<input
  #input
  type        ="text"
  id          ="searchInput"
  class       ="input-student-search validate filter-input"
  placeholder ="Search by a career (Software Engineer,Web Developer,Geologist, Geogropher etc.)"
  [(ngModel)] ="query"
>

Career-Search.component.ts

import {Component,OnInit,Input,EventEmitter} from '@angular/core';
@Component({
  selector: 'career-search',
  templateUrl: 'career-search.component.html'
})
export class CareerSearchComponent implements OnInit {
  @Input() public query: string;
  constructor() {}

  ngOnInit() {}

}

HomePageComponent.component.html

<career-search></career-search>
<button class="submit" [routerLink]="['/students']">Search</button>

Students-result.component.html

<career-search></career-search>

我需要从主页组件传递数据的原因是因为我可以使用数据来查询它并根据从其他组件传递的值显示结果。

请帮忙。

由于

1 个答案:

答案 0 :(得分:4)

如果您的两个组件没有任何其他连接,我知道的唯一方法是使用服务。 AJT_82提供的链接有一个例子,这是我能想到的最小的例子:

&#13;
&#13;
import {Component, Injectable, EventEmitter} from '@angular/core';

@Injectable()
export class InputService {

  public inputEvents: EventEmitter<string> = new EventEmitter();

  public inputChanged(val: string) {
    this.inputEvents.emit(val);
  }
}

@Component({
  selector: 'observer',
  template: `
    <p>Input value: {{ myValue }}</p>
`
})
export class ObserverComponent implements OnDestroy {

  private myValue: string;
  private subscription: Subscription;

  constructor(private service: InputService) {
    this.subscription = this.service.inputEvents.subscribe((newValue) => {
      this.myValue = newValue;
    })
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }
}

@Component({
  selector: 'observable',
  template: `
    <input [(ngModel)]="inputValue" />
`
})
export class ObservableComponent {

  private _inputValue: string;

  constructor(private service: InputService) {}

  public get inputValue(): string {
    return this._inputValue;
  }

  public set inputValue(val: string) {
    this._inputValue = val;
    this.service.inputChanged(val);
  }
}

@Component({
  selector: 'app-root',
  template: `

    <observable></observable>
    <observer></observer>

`
})
export class AppComponent {
}
&#13;
&#13;
&#13;

说明:

Observable Component通过双向数据绑定存储input-Value。在setter中,我们不仅存储值,还告诉服务值已更改。然后该服务将发出Observer订阅的inputChanged事件。然后它可以使用它喜欢的值。

相关问题