FormControl 上的 setValue 未反映在 View 中

setValue on FormControl is not reflected in View

我想将现有值加载到 FormControl 中以便能够更新数据库中的值。

我的代码(简化并归结为示例)如下所示。单击编辑按钮会将引用名称从数组加载到 FormControl 中。

应用组件

import { Component } from '@angular/core';
import {FormControl, ReactiveFormsModule} from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})

export class AppComponent  {

  nameForm = new FormControl(['']);
  names = ['Peter', 'Bob', 'Mary']

  updateName (id : number): void {
      this.nameForm.setValue(this.names[id]);
  }   
}

HTML-模板

 <table>
            <tr>
              <th>Id</th>
              <th>Name</th>
              <th>Actions</th>
            </tr>
            <tr *ngFor="let name of names; index as i">
                <td>{{i + 1}}  : </td><td>{{name}}</td>
                  <td>
                    <button (click)="updateName(i)">Edit</button>
                  </td>
            </tr>
    </table>
<input type="text" formControlName="nameForm">

我在 https://stackblitz.com/edit/angular-m7vm4y 上构建了一个示例。 单击编辑不会将值设置到 FormControl 中。我的错误在哪里?

谢谢,最好!

<input type="text" [formControl]="nameForm">

因为 formControlName 需要 formGroup。

您可以将表单包装在表单组中并使用它设置值。尝试以下

控制器

import { Component } from '@angular/core';
import {FormGroup, FormControl, ReactiveFormsModule} from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  form: FormGroup = new FormGroup({
    nameForm: new FormControl('')
  });
  names = ['Peter', 'Bob', 'Mary']

  updateName (id : number): void {
    this.form.get('nameForm').setValue(this.names[id]);
  }
}

模板

<table>
  <tr>
    <th>Id</th>
    <th>Name</th>
    <th>Actions</th>
  </tr>
  <tr *ngFor="let name of names; index as i">
    <td>{{i + 1}}  : </td><td>{{name}}</td>
    <td>
      <button (click)="updateName(i)">Edit</button>
    </td>
  </tr>
</table>
<form [formGroup]="form">
  <input type="text" formControlName="nameForm">
</form>

我修改了你的Stackblitz

简单修复,更改此行:

<input type="text" formControlName="nameForm">

对此:

<input type="text" [formControl]="nameForm">


formControlName 用作 FormGroup 的一部分,以有效地引用该组中的 child,字符串名称为 child,几乎在使用 object[ 'key' ]

将密钥传递给 object 的方式

如果您没有将 FormGroup 用作 FormControl 的 parent,那么您只需将 FormControl 绑定到 HTML 直接元素,因此方括号。

请尝试添加一个 FormGroup,如下所示:

HTML:

<form [formGroup]="form">
 <input type="text" formControlName="name">
</form>

TS:

name = new FormControl(['']);
names = ['Peter', 'Bob', 'Mary']
form: FormGroup;

constructor(private fb: FormBuilder){
 this.form=this.fb.group({
   name:['']
 })
}

updateName (id : number): void {
  this.form.get('name').setValue(this.names[id]);
}

更多信息请参考:

https://angular.io/guide/reactive-forms

希望对您有所帮助