首页 \ 问答 \ 在Angular 4中选择具有反应形式的下拉列表的值(Value of select drop down list with reactive forms in Angular 4)

在Angular 4中选择具有反应形式的下拉列表的值(Value of select drop down list with reactive forms in Angular 4)

我使用Angular 4中的ReactiveForms模块创建了一个表单。在我的.ts文件中:

myForm: FormGroup;
dataTypes: FormArray;

ngOnInit() {
  this.myForm = new FormGroup({});
  this.dataTypes = new FormArray([
      new FormControl("A"),
      new FormControl("B"),
      new FormControl("C")
  ]);
  this.myForm.addControl('dataTypes', this.dataTypes);
}

onSubmit() {
  console.log(this.myForm.value);
}

并在我的HTML:

<form [formGroup]="myForm" (ngSubmit)=onSubmit()>
  <select name="datatypes"
          id="datatypes"
          formArrayName="dataTypes">

          <option *ngFor="let dataType of myForm.get('dataTypes').controls;
                          let dataIndex=index"
                          [ngValue]="dataIndex">
                          {{ dataType.value }}
          </option>
  </select>

  <button type="submit">Submit</button>
</form>

在点击提交按钮时,我试图控制登录提交表单的值。 带有下拉列表的表单显示正确。 第一步是提取用户选择的drop drop列表的值。 但是console.log给出了一个包含所有三个值的数组,而不是所选的值。 myForm.value如何在提交时只有选定的dataTypes值?


I created a form using ReactiveForms module in Angular 4. In my .ts file:

myForm: FormGroup;
dataTypes: FormArray;

ngOnInit() {
  this.myForm = new FormGroup({});
  this.dataTypes = new FormArray([
      new FormControl("A"),
      new FormControl("B"),
      new FormControl("C")
  ]);
  this.myForm.addControl('dataTypes', this.dataTypes);
}

onSubmit() {
  console.log(this.myForm.value);
}

And in my html:

<form [formGroup]="myForm" (ngSubmit)=onSubmit()>
  <select name="datatypes"
          id="datatypes"
          formArrayName="dataTypes">

          <option *ngFor="let dataType of myForm.get('dataTypes').controls;
                          let dataIndex=index"
                          [ngValue]="dataIndex">
                          {{ dataType.value }}
          </option>
  </select>

  <button type="submit">Submit</button>
</form>

On clicking the submit button, I am trying to console log the value of the form submitted. The form with the drop down list is displayed correctly. The first step is to extract the value of the drop drown list selected by the user. But the console.log gives an array with all the three values and not the value selected. How will the myForm.value have only the selected value of dataTypes on submit?


原文:https://stackoverflow.com/questions/48379209
更新时间:2024-03-27 20:03

最满意答案

如果您有一个名为IngredientType的表单,您可以将其嵌入父表单中,如下所示:

$builder->add('ingredients', new IngredientType());

这对于可以多次重复使用的表单部分非常有用(即联系信息字段,在几种类型的表单中可能相同)

这是一个更全面的例子: http//symfony.com/doc/current/cookbook/form/form_collections.html


If you have a form called IngredientType, you can embed it in a parent form like this:

$builder->add('ingredients', new IngredientType());

This is super helpful for portions of forms that may be reused more than once (i.e. contact info fields, which may be identical in several types of forms)

Here's a more thorough example: http://symfony.com/doc/current/cookbook/form/form_collections.html

相关问答

更多
  • 如果硬件上有ManyToOne ,则MagazineStockTakingDetails会引用类型为Hardware的对象,因此您只能设置一个类型为硬件的对象,但您正在尝试设置ArrayCollection 。 这不起作用: ->add('hardware','collection',array( 'type' => new HardwareFormType(), 'allow_add' => true, 'by_reference' ...
  • 由于AddressType类中的这一行而发生此错误: ->add('address', TextType::class, array('label' => 'Adresse*', 'required' => true)) 您正在尝试访问Address实体的address属性,但它不包含它。 这与其他领域相关: CodePostal => postalCode等 同样在你的Shop实体你有一个注释为OneToMany关系的address字段,这是正常的,同时你有setAddress(ArrayCollecti ...
  • 如果您有一个名为IngredientType的表单,您可以将其嵌入父表单中,如下所示: $builder->add('ingredients', new IngredientType()); 这对于可以多次重复使用的表单部分非常有用(即联系信息字段,在几种类型的表单中可能相同) 这是一个更全面的例子: http : //symfony.com/doc/current/cookbook/form/form_collections.html If you have a form called Ingredie ...
  • 这是禁用所有标签的简单方法。 如果频繁使用,请将此方法添加到BaseForm 。 public function disableLabels() { $fields = $this->getWidgetSchema()->getFields(); $this->getWidgetSchema()->setLabels(array_combine(array_keys($fields), array_fill(0, count($fields), false))); } 如果您只想禁用嵌入表单中的标 ...
  • 您可以按如下方式访问上传的资产: $imageThumbFile = $form->get('imageThumb')->get('file')->getData(); $imageLargeFile = $form->get('imageLarge')->get('file')->getData(); 如果您打算将这些存储在数据库中作为blob,那么您可能会发现这个SO问题很有用: 如何使用Doctrine持久保存图像 或者,您可以将上载的文件存储在文件系统中,并按照菜谱条目如何使用Doctrine处理 ...
  • 你说,你的data_class是一个BenefitGroup $resolver->setDefaults(array( 'data_class' => 'AppBundle\Entity\BenefitGroup', )); 然后设置一个BenefitItem 。 $BI = new BenefitItem(); // ... $form = $this->createForm(new BenefitItemFormType(), $BI); 那不行。 我没有检查你的其余代码,但这也是异常所说 ...
  • 根据1.1或1.2 sfForm是一个独立的库(类),除非您从Doctrine / Propel sfForm扩展,否则它与您的数据库没有连接。 因为它是独立的,你可以按照你的意愿使用它,你只需要创建一个表单 类AddProductForm扩展了sfForm { } 并使用一个隐藏的小部件进行设置,该小部件将保存您的product_id和一个product_count文本输入,该输入应该是用户想要订购的产品数量。 然后,只需执行标准if($ form-> isValid()),然后将其插入到数据库和/或co ...
  • FOSUserBundle:Resetting:sendEmail期望用户名或电子邮件作为POST。 public function sendEmailAction(Request $request) { $username = $request->request->get('username'); /** @var $user UserInterface */ $user = $this->container->get('fos_user.user_manager') ...
  • 在我的表单中发现错误,因此可以选择此类表单: http : //symfony.com/doc/current/cookbook/form/inherit_data_option.html Found mistake in my form, so there is option for such type of forms: http://symfony.com/doc/current/cookbook/form/inherit_data_option.html
  • Form文件夹只是一个约定 - 您可以将表单放在任何地方。 该公约延伸至: Form\Type表单类型, Form\Model for form models , Form\Handler程序的Form\Handler , 等等 The Form folder is just a convention — you can put your forms wherever you want. The convention extends to: Form\Type for form types, Form\Mo ...

相关文章

更多

最新问答

更多
  • Runnable上的NetworkOnMainThreadException(NetworkOnMainThreadException on Runnable)
  • C ++ 11 + SDL2 + Windows:多线程程序在任何输入事件后挂起(C++11 + SDL2 + Windows: Multithreaded program hangs after any input event)
  • AccessViolationException未处理[VB.Net] [Emgucv](AccessViolationException was unhandled [VB.Net] [Emgucv])
  • 计算时间和日期差异(Calculating Time and Date difference)
  • 以编程方式标签NSMutableAttributedString swift 4(Label NSMutableAttributedString programmatically swift 4)
  • C#对象和代码示例(C# objects and code examples)
  • 在python中是否有数学nCr函数?(Is there a math nCr function in python? [duplicate])
  • 检索R中列的最大值和第二个最大值的行名(Retrieve row names of maximum and second maximum values of a column in R)
  • 给定md5哈希时如何查找特定文件(How to find specific file when given md5 Hash)
  • Python字典因某些原因引发KeyError(Python Dictionary Throwing KeyError for Some Reason)
  • 如何让Joomla停止打开新标签中的每个链接?(How do I get Joomla to stop opening every link in a new tab?)
  • DNS服务器上的NS记录不匹配(Mismatched NS records at DNS server)
  • Python屏幕捕获错误(Python screen capture error)
  • 如何在帧集上放置div叠加?(How to put a div overlay over framesets?)
  • 页面刷新后是否可以保留表单(html)内容数据?(Is it possible to retain the form(html) content data after page refreshed?)
  • 使用iTeardownMyAppFrame和iStartMyAppInAFrame在OPA5测试中重新启动应用程序超时(Restart app within OPA5 test using iTeardownMyAppFrame and iStartMyAppInAFrame timed out)
  • 自动拆分文本内容到列(Automatically splitting text content into even columns)
  • 在r中的循环中将模型名称分配给gbm.step(assigning model names to gbm.step in loop in r)
  • 昆明哪里有电脑等级考试二级C培训?
  • C ++模板实例化,究竟是什么意思?(C++ template instantiation, what exactly does it mean?)
  • 帮助渲染来自fields_for的部分内容(Help to render a partial from fields_for)
  • 将url.action作为json对象返回mvc(return url.action as json object mvc)
  • 使用.BAT中的.application文件类型运行ac#Console App(Run a c# Console App with .application file type from a .BAT)
  • 将bindingRedirect添加到.Net标准库(Adding a bindingRedirect to a .Net Standard library)
  • Laravel版本升级会影响您的控制器吗?(Laravel version upgrade affects your controller?)
  • imaplib.error:命令SEARCH在状态AUTH中非法,只允许在SELECTED状态(imaplib.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED)
  • 如何在eclipse debug impala前端
  • 如何通过Ajax API处理多个请求?(How to handle multiple requests through an Ajax API? [closed])
  • 使用Datetime索引来分析数据框数据(Using Datetime indexing to analyse dataframe data)
  • JS 实现一个菜单效果