我有一个与Firestore数据库同步的表单。现在,当有人更改“国籍”字段的值时,我想触发一些其他操作,例如:
this.profileFormStageOne.get('nationality').valueChanges.subscribe(val => {
if (val && val === 'Other') {
let alert = this.alertCtrl.create({
title: 'Your Nationality',
inputs: [
{
name: 'nationality',
placeholder: 'Your Nationality e.g. Brazilian',
},
],
buttons: [
{
text: 'Update Nationality',
handler: data => {
this.manualNationality = data.nationality;
console.log(this.manualNationality);
},
},
],
});
alert.present();
}
});
但是我也使用ngOnChanges()来修补具有以下形式的值:
/**
* Get initial form values
* Needs to run from ngOnChanges because User in an input & is not ready in constructor
*/
ngOnChanges() {
if (this.User) {
const profile: Profile = this.User.profile;
this.profileFormStageOne.patchValue({
nationality: profile.nationality,
问题是,如果“国籍”字段已设置为“其他”,则会在初始渲染(补丁值期间)中调用此方法。
是否有其他方法或方法可以触发选择更改?
答案 0 :(得分:0)
您可以像这样订阅国籍变更
this
.profileFormStageOne.controls['nationality'].valueChanges.subscribe(()=> {
// your login
})
答案 1 :(得分:0)
以这种方式在Angular 6中进行
首先,创建一个吸气剂
get nationality() {
this.profileFormStageOne.get('nationality');
}
现在
this.nationalityChange = this.nationality.valueChanges.subscribe((value: string) => {
if (value === 'other') {
// do your requirement
}
this.nationality.updateValueAndValidity();
});
您必须调用pathValue()
方法来设置ngAfterViewInit()
挂钩中的默认值
并且不要忘记取消订阅可观察的
ngOnDestroy() {
this.nationalityChange.unsubscribe();
}