【发布时间】:2018-08-12 22:18:06
【问题描述】:
我有两个同级组件,第一个组件有select 框,不同的option 绑定到一个名为selectedValue 的变量。当我更改第一个组件中选项的值时,我希望在第二个组件中更改相同的值。但是,第二个组件一直显示未定义的值。这两个兄弟组件同时具有ngOnInit。
这是我的代码:
component1.ts:
selectedValue: any;
tokens: Tokens;
constructor(
private apiService: ApiService,
private sharedService: SharedService
) {
}
ngOnInit() {
this.loadTokens();
this.sharedService.pair.next(this.selectedValue);
}
loadTokens() {
this.apiService.getTokens()
.subscribe((data: any) => {
this.tokens = data;
}, error => {
console.log(error);
});
}
component1.html:
<mat-select placeholder="Choose a pair" [(ngModel)]="selectedValue">
<mat-option>-- None --</mat-option>
<mat-option *ngFor="let token of tokens" [value]="token.shortName">
{{token.name}}
</mat-option>
</mat-select>
shared.service.ts:
@Injectable()
export class SharedService {
pair = new BehaviorSubject(null);
observable: Observable<any> = this.pair.asObservable();
}
component2.ts:
pair: any;
constructor(private sharedService: SharedService) {}
ngOnInit() {
this.sharedService.observable.subscribe((data) => {
this.pair = data;
console.log(this.pair);
});
}
【问题讨论】:
-
ngOnChanges 帮助您检测任何输入更改
-
hmm,我之前没用过,你知道有demo或者参考链接吗?谢谢
-
ngdev.space/… 试试这个
标签: angular