Angular - 从服务中重新填充表单输入

时间:2017-07-05 22:00:18

标签: javascript angular

我有一个基本的角度组件,允许有人在他们转到他们的个人资料并点击“编辑”后编辑用户的详细信息。

组件:

export class EditUserComponent implements OnInit {

    // Define our vars
    user: Users[];
    editUserForm: FormGroup;
    message: {};
    displayMessage = false;
    userID: number;
    errorMessage: any = '';

    constructor(
        private fb: FormBuilder,
        private _userService: UserService,
        private activatedRoute: ActivatedRoute
    ) {
    }

    ngOnInit(): void {

        // Get the userID from the activated route
        this.activatedRoute.params.subscribe((params: Params) => {
            this.userID = params['id'];
        });

        // Call our service and pass the UserID
        this._userService.getUser(this.userID)
            .then(res => {
                this.user = res;
                this.createForm();
            });

    }

    // Generate the form
    createForm() {
        this.editUserForm = this.fb.group({
            QID: ['', Validators.required],
            favoriteColor: [''],
            favoriteNumber: [''],
            favoriteActor: ['']
        });
    }

}

服务

// Fetch a single user
    getUser(userID: number) {
        return this._http.post(this.baseUrl + '/fetchUser', { "userID": userID }, { "headers": this.headers })
            .toPromise()
            .then(res => res.json())
            .catch(err => { this.handleError(err); });
    }

接口

export interface Users {
    RecordID?: number;
    QID: string;
    favoriteColor?: string;
    favoriteNumber?: number;
    favoriteActor?: string;
}

我正在尝试将值传递给我的formGroup但是我无法弄清楚如何访问这些值。

我假设我可以做这样的事情,我可以访问用户模型并从中选择一个属性,但这会引发一个未定义的错误。

我会在表格组中传递值,还是直接将它们绑定到元素?我收到服务中的数据就好了,只是不确定如何将每个值都恢复到各自的字段。

createForm() {
    this.editUserForm = this.fb.group({
        QID: [this.user.QID, Validators.required],
        favoriteColor: [''],
        favoriteNumber: [''],
        favoriteActor: ['']
    });
}

2 个答案:

答案 0 :(得分:1)

如果我理解正确......这就是我的代码:

onProductRetrieved(product: IProduct): void {
    if (this.productForm) {
        this.productForm.reset();
    }
    this.product = product;

    // Update the data on the form
    this.productForm.patchValue({
        productName: this.product.productName,
        productCode: this.product.productCode,
        starRating: this.product.starRating,
        description: this.product.description
    });
    this.productForm.setControl('tags', this.fb.array(this.product.tags || []));
}

我使用patchValue表示值,setControl表示数组。

OR

由于您在检索数据后创建表单,因此可以执行以下操作:

createForm() {
    this.editUserForm = this.fb.group({
        QID: [this.user.QID, Validators.required],
        favoriteColor: [this.user.favoriteColor],
        favoriteNumber: [this.user.favoriteNumber],
        favoriteActor: [this.user.favoriteActor]
    });
}

并且只是为了完成......每个输入元素需要一个formControlName属性,如下所示:

                    <input class="form-control" 
                            id="productNameId" 
                            type="text" 
                            placeholder="Name (required)" 
                            formControlName="productName" />
                    <span class="help-block" *ngIf="displayMessage.productName">
                            {{displayMessage.productName}}
                    </span>
                </div>

您可以在此处找到完整的工作示例:https://github.com/DeborahK/Angular2-ReactiveForms

答案 1 :(得分:0)

将提交事件绑定到表单,然后使用this.editUserForm.value访问表单中的数据。

在组件模板中:

<form [formGroup]="editUserForm" (submit)="saveIt()">

在组件中:

  saveIt() {
    if (this.editUserForm.dirty && this.editUserForm.valid) {
      alert(`Number: ${this.editUserForm.value.favoriteNumber} Actor: ${this.editUserForm.value.favoriteActor}`);
    }
  }