我正在根据某些条件从表单中添加/删除控件。
if(true) {
this.form.addControl('age', new FormControl(this.resp.age));
}
this.form.get('age').valueChanges.subscribe(val => {
//Do something.
});
因此,这里确切需要的是添加控件时,我需要触发与此控件相关的值更改。我知道添加此控件并设置了值之后,valuechanges才在该范围内,并在以后出现。因此,在添加控件时可以执行什么操作来触发它。
答案 0 :(得分:1)
valueChanges需要由...触发,嗯,一个值更改。但是您可以使用运算符来更改它:
this.form.get('age').valueChanges
.pipe(startWith(this.form.get('age').value))
.subscribe(value => {...});
在我的项目中,我实际上为这些问题做了几个RxJS运算符,这是一个:
export function firstValueOfControl<T>(control: AbstractControl) {
return control.valueChanges.pipe(startWith(control.value));
}
...
firstValueOfControl(this.form.get('age')).subscribe(value => {...});
没有看到if value's present
部分。只需添加一个过滤器:
this.form.get('age').valueChanges
.pipe(startWith(this.form.get('age').value), filter(v => !!v)
.subscribe(value => {...});
对于运营商:
export function filterTruthy<T>() {
return filter<T>(v => !!v);
}
firstValueOfControl(this.form.get('age'))
.pipe(filterTruthy())
.subscribe(value => {...});
答案 1 :(得分:0)
在模板中使用ngFor并绑定动态formControlName。
模板:
<form [formGroup]="formGroup">
...
<ul>
<li *ngFor="let question of questions">
<input [formControlName]="questions.id">
</li>
</ul>
...
</form>
组件:
const questions = [{id: 1}, {id: 2}]; // just for demo
this.formGroup = this.fb.group(
questions.reduce((acc, curr) => ({ ...acc, [curr.id]: '' }), {})
);
这将基于以下对象生成formGroup:{1:“”,2:“”,3:“”}。如果需要,还可以为表单控件设置初始值:
const questions = [{id: 1, value: 'q1'}, {id: 2, value: 'q2'}]; // just for demo
this.formGroup = this.fb.group(
questions.reduce((acc, curr) => ({ ...acc, [curr.id]: curr.value }), {})
);