【问题标题】:Reactive form how to submit additional data反应式表单如何提交附加数据
【发布时间】:2016-12-26 16:21:29
【问题描述】:

我有这个提交单个值的响应式表单,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

【问题讨论】:

  • default 值是什么意思?
  • 无论标题是什么,类型都是“讨论”。像这样 {title:'this is just string', type:'disucssion'}

标签: angular


【解决方案1】:

只需将构造函数更改为:

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

【讨论】:

    【解决方案2】:

    您可以执行以下操作,在 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)
    }
    

    让我知道这是否符合您的需求!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-22
      • 2019-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      • 2020-04-06
      相关资源
      最近更新 更多