反应式表单如何提交其他数据

时间:2016-12-26 16:21:29

标签: angular

我有这种反应形式,提交单个值,title

@Component({
    template: `
        <form [formGroup]="formGroup" (ngSubmit)="onSubmit()" novalidate>
            <input class="form-control" placeholder="title" name="title" id="title" formControlName="title" />
            <div *ngIf="formGroup.controls['title'].dirty && formGroup.controls['title'].invalid">This is required</div>
            <button type="submit">Create</button>
        </form>
    `,
})
export class CreateDiscussionComponent {

    formGroup: FormGroup;

    constructor() {
        this.formGroup = new FormGroup({
            title: new FormControl('', [Validators.required, Validators.minLength(1)])
        });
    }
    onSubmit(): void {
        console.log('form value', this.formGroup.value)
    }
}

如果我想向formGroup对象添加额外的default值,该怎么办?喜欢类型:'讨论'。

所以当我提交时,我希望在控制台中有这样的东西

{title:'bla bla bla', type:'discussion'}

怎么做?

https://plnkr.co/edit/RY62cBHMTLLjaDCIA6mc?p=preview

2 个答案:

答案 0 :(得分:3)

只需将构造函数更改为:

constructor() {
        this.formGroup = new FormGroup({
          title: new FormControl('', [Validators.required, Validators.minLength(1)]),
          type : new FormControl('discussion')
        })
    }

答案 1 :(得分:1)

您可以执行以下操作,在FormGroup定义中添加类型,并在onSubmit()方法中设置值。像这样:

formGroup: FormGroup;

constructor() {
    this.formGroup = new FormGroup({
        title: new FormControl('', [Validators.required, Validators.minLength(1)]),
        type: new FormControl('')
    });
}
onSubmit(): void {
    (<FormControl>this.formGroup.controls['type']).setValue("discussion");
    console.log('form value', this.formGroup.value)
}

如果符合您的需求,请告诉我们!