将反应形式值转换为模型属性类型

时间:2019-11-15 22:47:11

标签: angular typescript angular8

使用Angular 8,我有一个带有表单的组件来创建帖子。

帖子模型具有3个属性:一个字符串,一个布尔值和一个数字:

export interface PostModel {
  title: string
  year: number;
  approved: Boolean;  
}

问题是,当我从表单值创建PostModel时,所有内容都被视为字符串:

  let model: PostModel = { 
    title: this.form.value.title,
    approved: this.form.value.approved,
    year: this.form.value.year
  };

如何从表单值创建PostModel并使用PostModel属性类型?

这是组件代码:

export class PostCreateComponent extends Modal implements OnInit {

  form: FormGroup;

  constructor(private formBuilder: FormBuilder, private postService: PostService) { }

  ngOnInit() {

    this.form = this.formBuilder.group({  
      title: [''],
      year: [''],
      approved: ['']
    });

  }

onSubmit() {

  if (this.form.valid) {

    let model: PostModel = { 
      title: this.form.value.title,
      approved: this.form.value.approved,
      year: this.form.value.year
    };

    // Create post

  }

}

2 个答案:

答案 0 :(得分:1)

  1. 您是否在html中使用type =“ number”?
  2. 如果上一步不起作用,我建议您进行转换
value: number = +year;
// The + is for converting a string to a number

答案 1 :(得分:0)

不幸的是,FormControl值的类型仅为any。但是,一种解决方法可能是扩展类并添加类型限制:

class TypedFormControl<T> extends FormControl {
    get value(): T | null {
        return super.value;
    }

    get valueChanges(): Observable<T | null> {
        return super.valueChanges;
    }
}

export class PostCreateComponent {
    readonly yearControl = new TypedFormControl<number>();
    readonly form = new FormGroup({
        year: this.yearControl,
        ...
    })

    ...

    onSubmit() {
        ...
        const post: PostModel = {
            year: this.yearControl.value,
            ...
        }
    }
}