Angular2中多个组件之间的两种数据结合



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

我想到为输入创建一个单独的组件并在两个组件中调用它们,但是当我开始在HomePageComponent中键入时,该值并未在我的学生resultscomponent中更新。这是我的代码:

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>

我需要从主页组件传递数据的原因是,因为然后我可以使用数据查询并根据从另一个组件传递的值来显示结果。

请帮助。

谢谢

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

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

说明:

可观察的组件通过双向数据结合存储输入值。在设定器中,我们不仅存储该值,而且还告诉服务值已更改。然后,该服务将发出一个输入的事件,观察者订阅。然后可以使用该值,但是喜欢。

最新更新