渲染后将反应形式值绑定到html

时间:2017-08-08 21:36:33

标签: angular angular-ng-if angular-reactive-forms

我在.ts文件中创建了一个反应形式,然后将要绑定的html控件和表单保存在* ngIf块中。如果用户点击编辑,则会显示该表单并提交新值。

目前,表单正在提交空值。我猜这是因为当没有呈现html时,表单无法绑定到html。我如何解决这个问题才能正确绑定?

.ts片段

    export class DhcpComponent implements OnInit {
        edit = '';

        editEntryForm: FormGroup;

        constructor(private networkService: NetworkService){}

        ngOnInit() {
            this.editEntryForm = new FormGroup({
                'newHostname': new FormControl(null, Validators.required),
                'newMac': new FormControl(null, Validators.required),
                'newIp': new FormControl(null, Validators.required)
            });

            console.log(this.editEntryForm);
        }

        addEditedEntry(entryEdit) {
            console.log(entryEdit);
        }

        editEntry(entry) {
           // change to edit mode on entry
           this.edit = entry.hostname;
        }
    }

.html代码段

<button
                        type="button"
                        class="btn-default btn"
                        (click)="editEntry(entry)"
                    >
                        <i class="fa fa-pencil-square-o"></i>
</button>

<form
            class="edit dhcp-item row"
            *ngIf="edit === entry.hostname"
            [formGroup]="editEntryForm"
            (ngSubmit)="addEditedEntry(editEntryForm)"
        >
            <div class="update-col col">
                <button type="submit" class="update-sub btn btn-secondary">
                    Update
                </button>
            </div>
            <div class="col">
                <input
                    type="text"
                    value="{{ entry.hostname }}"
                    class="form-control"
                    formControlName="newHostname"
                >
            </div>
            <div class="col">
                <input
                    type="text"
                    value="{{ entry.mac }}"
                    class="form-control"
                    formControlName="newMac"
                >
            </div>
            <div class="col">
                <input
                    type="text"
                    value="{{ entry.ip }}"
                    class="form-control"
                    formControlName="newIp"
                >
            </div>
</form>

2 个答案:

答案 0 :(得分:1)

通过将大括号插值移除到输入标记的value参数来解决此问题:

删除:value="{{ entry.hostname }}"

要动态添加值,请在每个编辑按钮上单击使用设置值:

editEntry(entry) {
        // change to edit mode on entry
        this.edit = entry.hostname;
        this.editEntryForm.setValue({
            'newHostname': entry.hostname,
            'newMac': entry.mac,
            'newIp': entry.ip
        });
}

插值导致值为null,因为angular每次都试图获取最后一个循环条目的值(感谢@sancelot指出它)。

答案 1 :(得分:0)

绑定隐藏属性而不是使用ngIf

[hidden]="!showIt"