【问题标题】:Angular : How to access the value of controls in nested formsAngular:如何访问嵌套表单中控件的值
【发布时间】:2020-04-04 15:46:35
【问题描述】:

我正在尝试在控制台和 HTML 中打印获取嵌套表单的表单控件的值。

userForm = new FormGroup({
    name: new FormControl("Tom Alter"),
    address: new FormGroup({
        Country: new FormControl("India"),
        State: new FormControl("Delhi")
    })
});

在这两种情况下,我都可以使用 get 语句找到值。

console.log ("name : ", this.userForm.controls.name.value);
console.log ("Country using Get Way 1  : ", this.userForm.get(['address', 'Country']).value) ;
console.log ("Country using Get Way 2 : ", this.userForm.get(['address']).get(['Country']).value);
console.log ("Country using Get Way 3 : ", this.userForm.get(['address.Country']).value);
console.log ("Country without Get: ", this.userForm.group.address.controls.cCountry.value);

在这些“名称”、“方式 1”、“方式 2”中,“方式 3”和“无获取”不起作用,因为它正在为“名称”工作

在 HTML 中类似:

Name : {{userForm.controls.name.value}}
<br>
<br>
Country with get Way - 1 : {{userForm.get(['address']).get(['Country']).value}}
<br>
Country with get Way - 2 : {{userForm.get(['address','Country']).value}}
<br>
<br>
Country without get: {{userForm.address.controls.country.value}}

name 和 Way 1 工作正常,而“Way-2”和“Without get”不起作用。

请指出我在代码中的错误。

代码可在https://stackblitz.com/edit/angular-nestedformgroups获取

【问题讨论】:

    标签: angular angular-reactive-forms


    【解决方案1】:

    方式3应该没有数组

    this.userForm.get('address.Country').value
    

    没有Get的国家可以通过controlls访问

    this.userForm.controls.address.controls.Country.value
    

    在模板中只是一个小错误。你应该有Country 而不是country 并且还可以通过.controls 属性访问

    {{userForm.controls.address.controls.country.value}}
    

    【讨论】:

      【解决方案2】:

      我们在工作中遇到了很多关于表单和嵌套表单的问题。 在围绕该主题进行了大量研究以简化我们的生活之后,我们提出了一个我们决定开源的库。它是一个超小型的包装器,可用于响应式或模板表单(不过肯定会推荐响应式)。

      这个库被称为 ngx-sub-form:https://github.com/cloudnc/ngx-sub-form 自述文件应包含您发现该库所需的所有内容,但我还在这里写了一篇文章:https://dev.to/maxime1992/building-scalable-robust-and-type-safe-forms-with-angular-3nf9 以了解更多详细信息。

      现在,我已将您的 stackblitz 转换为使用 ngx-sub-form,如下所示:

      https://stackblitz.com/edit/user-nested-form-group?file=src/app/app.component.ts

      代码:

      app.component.ts

      @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: [ './app.component.css' ]
      })
      export class AppComponent  {
        public userUpdate(user: User): void {
          // every time the form changes
          // this method will be called
          console.log(user);
        }
      }
      

      app.component.html

      <app-user-form (userUpdate)="userUpdate($event)"></app-user-form>
      

      user-form.component.ts

      @Component({
        selector: "app-user-form",
        templateUrl: "./user-form.component.html",
        styleUrls: ["./user-form.component.css"]
      })
      export class UserFormComponent extends NgxAutomaticRootFormComponent<User> {
        @DataInput()
        @Input("user")
        public dataInput: Required<User>;
      
        @Output("userUpdate")
        public dataOutput: EventEmitter<User> = new EventEmitter();
      
        protected getFormControls(): Controls<User> {
          return {
            name: new FormControl(null),
            address: new FormControl(null),
          };
        }
      }
      

      user-form.component.html

      <div [formGroup]="formGroup">
        <input type="text" [formControlName]="formControlNames.name" placeholder="Name">
        <app-address-control type="text" [formControlName]="formControlNames.address" placeholder="Address"></app-address-control>
      </div>
      
      <pre>{{ formGroupValues | json}}</pre>
      
      <!-- So you can simply do: -->
      
      <ul>
        <li>Name: {{ formGroupValues.name }}</li>
        <li>
          Address
          <ul>
            <li>Country: {{ formGroupValues.address.country }}</li>
            <li>State: {{ formGroupValues.address.state }}</li>
          </ul>
        </li>
      </ul>
      

      在上面,请注意访问嵌套值是多么容易

      address-control.component.ts

      @Component({
        selector: "app-address-control",
        templateUrl: "./address-control.component.html",
        styleUrls: ["./address-control.component.css"],
        providers: subformComponentProviders(AddressControlComponent)
      })
      export class AddressControlComponent extends NgxSubFormComponent<
        Address
      > {
        protected getFormControls(): Controls<Address> {
          return {
            country: new FormControl(null),
            state: new FormControl(null)
          };
        }
      }
      

      address-control.component.html

      <div [formGroup]="formGroup">
        <input type="text" [formControlName]="formControlNames.country" placeholder="Country">
        <input type="text" [formControlName]="formControlNames.state" placeholder="State">
      </div>
      

      这里不是解释库的所有特性的地方,所以我会让你深入阅读自述文件或文章,但这样做你在使用 AoT 和更多东西时也会获得额外的类型安全性。

      查看演示时,还请打开控制台,看看您可以在表单更改时轻松做出反应。

      【讨论】:

        【解决方案3】:

        对于没有 get 的国家/地区: 将“{{userForm.address.controls.country.value}}”替换为{{userForm.controls['address'].controls['Country'].value}}

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-02-21
          • 2018-03-08
          • 2019-02-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多