我有两个组件 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"
>
职业搜索.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 {
}
说明:
可观察组件通过双向数据绑定(bind)存储输入值。在 setter 中,我们不仅存储值,还告诉服务值已更改。然后,该服务将发出一个 inputChanged 事件,观察者会订阅该事件。然后它可以随意使用该值。
关于angular - Angular2中多个组件之间的两种方式数据绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42814978/