0

我坚持使用 Angular5 ReactiveForm。
实际上,我创建了一个基本模型子

子模型.ts

export interface Subscription {
    name: string;
}

我也有一个组件: : sub.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { Sub } from '@models/sub.model';

@Component({
    selector: 'md-subscribe',
    templateUrl: './subscribe.component.html',
    styleUrls: ['./subscribe.component.scss']
})
export class SubComponent {

    subForm: FormGroup;
    sub: Subscription;

    constructor(private builder: FormBuilder) {
        this.subForm = this.builder.group({
            name : ['', Validators.required]
        });
    }

    subscribe() {
        this.sub.name = 'test value';
    }

}

最后,一个 html 模板:

<form class="form align-end" [formGroup]="subscribeForm" (ngSubmit)="subscribe()">
    <h2 class="label label--blue">S'inscrire</h2>
    <div class="form-group"><input type="text" id="name" name="name" formControlName="name" placeholder="Hubert" required /></div>
</form>

所以我尝试提交表格。我可以使用 获取值,this.subForm.value但是当我尝试分配值时test valuethis.subForm.value.name我在控制台中出现错误。

ERROR TypeError: Cannot set property 'email' of undefined
    at SubscribeComponent.subscribe (subscribe.component.ts:24)
    at Object.eval [as handleEvent] (SubscribeComponent.html:1)
    at handleEvent (core.js:13581)
    at callWithDebugContext (core.js:15090)
    at Object.debugHandleEvent [as handleEvent] (core.js:14677)
    at dispatchEvent (core.js:9990)
    at eval (core.js:12332)
    at SafeSubscriber.schedulerFn [as _next] (core.js:4351)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:240)
    at SafeSubscriber.next (Subscriber.js:187)

事实上,我的对象 sub 是未定义的,但为什么我不能赋值。我也更改了 zone.js 版本,但问题仍然存在。我如何分配价值?

4

2 回答 2

1

我认为这是因为您使用了错误的对象。你只有 sub 的声明。在您的组件中应该是:

sub: Subscription = <Subscription>{name:""} ;
subscribe() {
    this.sub.name = this.subForm.value.name;
}

这是没有错误的示例https://stackblitz.com/edit/angular-atjwke

于 2018-01-19T09:52:37.423 回答
1

当我使用 ReactiveForms 时,我喜欢有两个变量:data 和 dataForm(在你的情况下是 sub 和 subForm)和一个函数 buildForm

subForm: FormGroup;
sub: Subscription;

constructor(private builder: FormBuilder) {}
//For example in ngOnInit
ngOnInit()
{
     this.buildForm();
}
//or when we subscribe
subscribe() {
    this.sub.name = 'test value';  //<--give value to the "data"
    this.subForm=this.buildForm(this.sub);  //<--create a groupForm with the data
}
//Our function buildForm return a formGroup
buildForm(sub:Subscription|null)
{
   return this.builder.group({
      name : [sub? sub.name:'', Validators.required]
   })
}
于 2018-01-19T10:16:12.877 回答