【问题标题】:Get the HTML content of an Angular form获取 Angular 表单的 HTML 内容
【发布时间】:2021-12-30 07:46:06
【问题描述】:

我有一个像下面这样的角度形式

<div #myForm [formGroup]="myForm">        
        <select formControlName="productName" class="form-control">
            <option value="">Select</option>
            <option *ngFor="let item of productNames" [value]="item.value"
                [textContent]="item.text"></option>
        </select>
    </div>
    <button (click)="Print()">Print</button>

单击按钮时,我想获取表单 html,以便可以在其他地方使用它。所以我使用表单引用来获取如下的innerHtml。

import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-print-form',
  templateUrl: './print-form.component.html',
  styleUrls: ['./print-form.component.css']
})
export class PrintFormComponent implements OnInit {
  myFormGrp: FormGroup;
  productNames:  any[];
  @ViewChild('myForm') myForm: ElementRef<HTMLDivElement>;
  constructor(private formBuilder:FormBuilder) { }

  ngOnInit(): void {
    this.productNames = [
      {text: "aaa", value: "1"},
      {text: "bbb", value: "2"},
      {text: "ccc", value: "3"},
      {text: "ddd", value: "4"}
    ];

    this.myFormGrp = this.formBuilder.group({
      productName: new FormControl({ value: '3', disabled: false })
    });
  }

  Print(): void {
     console.log(this.myForm.nativeElement.innerHTML);
  }

}

但是 innerText 不返回下拉列表的选定值。有没有办法获取表单控件的选定值?

【问题讨论】:

    标签: angular typescript angular-forms


    【解决方案1】:

    我看到你正在使用 reactivform。您应该像这样添加(ngSubmit) 事件监听器:

    <form [formGroup]="myForm" (ngSubmit)="print()">
    

    此外,您的方法不应使用大写字母(print() and not Print())

    然后您可以像这样检索表单的值:

    console.log(this.myForm.get('the_value_to_retrieve').value);
    

    angular doc很详细:https://angular.io/guide/reactive-forms

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2015-05-28
      • 2016-05-29
      • 1970-01-01
      • 2010-12-17
      • 2018-08-28
      相关资源
      最近更新 更多