我有一个示例表格,如下所示:
stuff: IStuff;
buildForm() {
this.createForm = this.form.group({
Val1: [{ value: '', disabled: true }],
Val2: [{ value: '', disabled: true }]
});
如您所见,两个值都设置为禁用。
构造函数触发httpClient获取并填充模型:
this.exampleHttpService.getStuff()
.subscribe(stuff => this.stuff = stuff);
东西在哪里:
export interface IStuff {
Val1?: number;
Val2?: number
}
Val1和Val2的绑定均在html中完成,如下所示:
<input name="Val1" matInput formControlName="Val1" [value]="stuff?.Val1">
这全是上帝,它很好地分配了值并将其显示在屏幕上;但是,当我尝试使用
找回这些值时this.createForm.getRawValue()
我得到''两个值都为空字符串...
有什么主意吗?
答案 0 :(得分:1)
从服务中获取数据后,是否在FormControls上设置setValue?从我看到的代码中,您正在将FormControls初始化为空字符串,这使我猜测您可能未设置值吗?
答案 1 :(得分:1)
使用反应式表单时,输入值已经绑定到表单控件,您不需要(也不应该)绑定到输入值,因为值和表单控件不是同一回事。在您的代码中,您正在初始化绑定到输入值的“东西”,但没有在初始化表单控制值。您需要初始化表单控件值:
let arr = [{ id: 3, sourceAccount: 'A', targetAccount: 'B', amount: 100, category: 'eating_out', time: '2018-03-02T10:34:30.000Z'},{ id: 1, sourceAccount: 'A', targetAccount: 'B', amount: 100, category: 'eating_out', time: '2018-03-02T10:33:00.000Z'},{ id: 6, sourceAccount: 'A', targetAccount: 'C', amount: 250, category: 'other', time: '2018-03-02T10:33:05.000Z'},{ id: 4, sourceAccount: 'A', targetAccount: 'B', amount: 100, category: 'eating_out', time: '2018-03-02T10:36:00.000Z'},{ id: 2, sourceAccount: 'A', targetAccount: 'B', amount: 100, category: 'eating_out', time: '2018-03-02T10:33:50.000Z'},{ id: 5, sourceAccount: 'A', targetAccount: 'C', amount: 250, category: 'other', time: '2018-03-02T10:33:00.000Z'}];
let res = []
, getKey = ({id, time, ...rest}) => Object.entries(rest).map(([k, v]) => k + '-' + v).join(';')
, getTimeDiff = (t1, t2) => Math.abs(new Date(t1).getTime() - new Date(t2).getTime())
arr.sort((a,b) => {
let akey = getKey(a)
, bkey = getKey(b)
return akey.localeCompare(bkey) || +new Date(a.time) - +new Date(b.time)
})
.forEach((d, i, t) =>
i == 0 ||
(getKey(d) == getKey(t[i-1]) && getTimeDiff(t[i-1].time, d.time)/1000 < 60)
? res.push((res.pop() || []).concat(d))
: res.push([d])
)
console.log(res)
答案 2 :(得分:0)
初始化反应式表单的正确方法是:
stuff: IStuff;
buildForm() {
//Get value for stuff before initializing form
this.createForm = this.form.group({
Val1: [{ stuff.Val1: '', disabled: true }],
Val2: [{ stuff.Val2: '', disabled: true }]
});
这里另一个值得注意的点是,为了获取表单的值,this.createForm.value
不会为禁用的控件提供更新的值。 this.createForm.getRawValue()
是这种情况下的选项。