触发valueChange with Initialized value – angular2
我正在写一个angular2应用程序而且我遇到了什么.
首先,我有一个绑定到formControl的select: export class MyComponent implements OnInit { profilesBy: Observable<any[]>; myControl = new FormControl(); constructor(public http: Http) { this.profilesBy = this.myControl.valueChanges .map(text => new formatQuery(text.value)) .switchMap(body => this.getGroupBy(body,this.url),(_,res)=> res.json().aggregations.group_by_type.buckets); } } 所以,myControl是formControl,profilesBy是一个Observable of array. 这是我的模板: <md-card> <h4>Profiles group by : <select [formControl]="myControl"> Some options ... </select> </h4> <div *ngFor="let profile of profilesBy | async"> <strong>{{profile.key}} :</strong> {{profile.doc_count | number:'1.0-2'}} </div> </md-card> 当用户选择一个值时它会正常工作,它会触发valueChange并链接动作! 所以我很高兴.我认为这是一种优雅的方式,而不是使用ngOnChanges() 现在,我无法找到使其有效的方法.基本上,我想用值初始化select并触发(没有任何用户操作)valueChange 我试图使用[(ngModel)]:< select [formControl] =“myControl”[(ngModel)] =“selectedGroupBy”> 最后,我尝试在方法ngOnInit()中自己调用 this.getGroupBy(new formatQuery(this.selectedGroupBy.value),this.url) .subscribe((response) => { this.profilesBy = response.json().aggregations.group_by_type.buckets; }); 但我有一个数组而不是一个Observable of Array!我错过了什么? 感谢您阅读本主题,对不起英语也不好意思! 可能的解决方案 : this.profilesBy = this.myControl.valueChanges .startWith(DEFAULT) .map(text => new formatQuery(text.value)) .switchMap(body => this.getGroupBy(body,res)=> res.json().aggregations.group_by_type.buckets); 解决方法
可能的解决方案是使用
startWith运算符:
this.profilesBy = this.myControl.valueChanges .startWith(DEFAULT_OPTION) .map(text => new formatQuery(text.value)) .switchMap(body => ...); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |