【问题标题】:Angular - Re-Populate form inputs from serviceAngular - 从服务重新填充表单输入
【发布时间】:2017-12-09 17:43:45
【问题描述】:

我有一个基本的 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: ['']
    });
}

【问题讨论】:

    标签: javascript angular


    【解决方案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 作为数组。

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

    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

    【讨论】:

    • 因此,您使用this.user.QID 的第二个示例是我的理想解决方案,也是我首先尝试的,但我收到“'Users[]' 类型上不存在属性'QID'”的错误。 .我认为它是正确的,因为它在我的界面中定义。
    • 这正是它所说的吗?如果是这样,那么它认为this.user 是一个数组。你是从getUser 得到一个数组而不是得到一个用户吗?
    • 哦...我明白了...您已将其声明为顶部的数组:user: Users[]; 如果它不应该是数组,则将其更改为user: Users(没有数组)。
    • 啊,很好,这有效:QID: [this.user[0].QID, Validators.required],
    【解决方案2】:

    将提交事件绑定到您的表单,然后使用 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}`);
        }
      }
    

    【讨论】:

    • 这看起来像反应形式......所以不需要从模板中传递它。
    • 我不想将值输入到表单中。这个页面有一些我需要从数据库(服务调用)中填写的输入字段,以便可以更新它们。本质上,我将这些字段的值设置为从数据库中获取的值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 2020-06-06
    • 2018-03-08
    • 2015-06-23
    • 2018-04-24
    • 1970-01-01
    相关资源
    最近更新 更多