返回Angular反应形式的选定选定属性内的所有对象值

时间:2019-11-14 09:54:53

标签: javascript angular typescript angular-reactive-forms reactive-forms

我有一个简单的动态单选按钮,在我的示例3中是从返回数据创建的。

选择单选值时,它将在我的反应式表单中填充该值,即“是”,“否”或“也许”。在这些对象中,我还希望将其他属性作为表单的一部分发送回去。

如下所示,我返回section,但也想返回匹配的sectionCode中的section

在更改单选之前,我的表单可以正确显示所有属性,但是很明显,我只能传递一个值,这样一来,其他对象项就会丢失。

https://stackblitz.com/edit/angular-r4g6uv?file=src%2Fapp%2Fpersonal%2Fpersonal.component.ts

section:[
        {
          section: "yes",
          sectionCode: "1"
        },
        {
          section: "no",
          sectionCode: "2"
        },
        {
          section: "maybe",
          sectionCode: "3"
        }
      ]

component.html

<div formGroupName="radioButtons" class="form-group col-6 pl-0 pt-3">
    <h2 class="mb-2">radioButtons</h2>
    <label for="intel-form-submitter" appRequiredLabel>select</label><br />
    <div class="form-check-inline" *ngFor="let item of personal.radioButtons.section">
        <label for="{{item.section}}" class="col-12 customradio"
            ><span>{{item.section}}</span>
            <input value="{{item.section}}" id="{{item.section}}" type="radio" formControlName="section"/>
            <span class="checkmark"></span>
        </label>
    </div>
</div>

component.ts

  createEntry(formBuilder: FormBuilder) {
    return this.formBuilder.group({
      title: this.personal.title,
      creationDate: this.personal.creationDate,
      radioButtons: this.formBuilder.group({
       section: this.personal.radioButtons.section,
      })
    });
  }

2 个答案:

答案 0 :(得分:1)

希望这对您有所帮助。

绑定对象,而不是对象中的一个值。在Component.html

  

[value] =“商品”

Component.html

<form [formGroup]="form" novalidate>
    <div formGroupName="radioButtons" novalidate>

        <div class="form-check-inline" *ngFor="let item of section">
            <label for="{{item.section}}" class="col-12 customradio"
            ><span>{{item.section}}</span>
            <input **[value]="item"** id="{{item.section}}" type="radio" formControlName="section"/>
            <span class="checkmark"></span>
        </label>
        </div>

    </div>

  <button type="button" (click)="save()" >Save</button>

</form>

{{form.value|json}}

Component.ts

xport class AppComponent implements OnInit {
  section = [
    {
      section: "yes",
      sectionCode: "1"
    },
    {
      section: "no",
      sectionCode: "2"
    },
    {
      section: "maybe",
      sectionCode: "3"
    }
  ];

  selectedSection: any;
  form: FormGroup;

  constructor(public formBuilder: FormBuilder) {}

  ngOnInit() {
    this.form = this.createEntry();
  }

  createEntry() {
    return this.formBuilder.group({
      radioButtons: this.formBuilder.group({
        section: this.section[0]
      })
    });
  }

  save(){
    console.log(this.form)
  }
}

在-https://stackblitz.com/edit/k-react-form-radio-test-5bixbv

中查找项目

答案 1 :(得分:0)

您可以绑定对象本身,而不仅仅是部分名称。

<input [value]="item" id="{{item.section}}" type="radio"/>

演示:https://stackblitz.com/edit/angular-h1mwhe