简体   繁体   中英

Angular - Re-Populate form inputs from service

I have a basic angular component that allows some one to edit the details of a user once they go to their profile and click on "edit".

Component:

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: ['']
        });
    }

}

Service:

// 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); });
    }

Interface:

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

I am trying to pass the values to my formGroup but I am having trouble figuring out how to access the values.

I assumed I could do something like this where I could access the user model and select a property from it but that is throwing an undefined error.

Would I pass the values here in the form group or bind them to the elements directly somehow? I am receiving the data back from the service just fine, just not sure how to get each of the values back to their respective fields.

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

If I understand correctly ... this is what my code looks like:

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 || []));
}

I'm using patchValue for the values and setControl for the array.

OR

Since you are creating the form after retrieving the data, you could do something like this:

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

AND just to be complete ... each input element needs a formControlName property like this:

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

You can find a complete working example here: https://github.com/DeborahK/Angular2-ReactiveForms

Bind a submit event to your form, then use this.editUserForm.value to access the data from the form.

In the component template:

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

In the Component:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM