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

Bind reactive form values to html after render

我在 .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>

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

[hidden]="!showIt"

此问题已通过删除输入标签值参数的花括号插值得到解决:

删除: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
        });
}

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