angular - 如何从动态 HTML 中获取表单值 Angular2

标签 angular typescript

我是 Angular 2 的新手,我正在努力从动态 HTML 中获取值。我的要求是我将有一些表单输入,并且我需要在其中插入动态 HTML,其中将包含更多输入。

我使用了 @Rene Hamger 的示例并创建了动态表单输入。

如果您查看示例,模板中有 3 个输入 2(姓名、姓氏)。我正在使用 addcomponent 注入(inject)地址。

我正在使用 Form Builder 构建所有 3 个控件,但是当您单击“提交”时,您可以看到显示“名称”和“姓氏”值,但无法获取地址值。

我现在不确定如何获取这些值。我请求社区专家帮助我。

http://plnkr.co/edit/fcS1hdfLErjgChcFsRiX?p=preview

app/app.component.ts

import {AfterViewInit,OnInit, Compiler, Component, NgModule, ViewChild,
  ViewContainerRef} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { FormGroup, FormControl, FormArray, FormBuilder, Validators } from '@angular/forms';
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";

@Component({
  selector: 'my-app',
  template: `
    <h1>Dynamic template:</h1>

    <form [formGroup]="myForm" (ngSubmit)="onSubmit()">
     <div  class="form-row">
      <label for="">Name</label>
      <input type="text" class="form-control" formControlName="name">
            <small [hidden]="myForm.controls.name.valid || (myForm.controls.name.pristine && !submitted)" class="text-danger">
            Name is required (minimum 5 characters).
          </small>
    </div>

        <div  class="form-row">
      <label for="">Last Name</label>
      <input type="text" class="form-control" formControlName="lastname">
            <small [hidden]="myForm.controls.name.valid || (myForm.controls.name.pristine && !submitted)" class="text-danger">
            Name is required (minimum 5 characters).
          </small>
    </div>

       <div #container></div>

      <div class="form-row">
      <button type="submit">Submit</button>
      </div>
       <div *ngIf="payLoad" class="form-row">
            <strong>Saved the following values</strong><br>{{payLoad}}
        </div>


    </form>
  `,
})
export class AppComponent implements OnInit , AfterViewInit {
  @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
  public myForm: FormGroup; // our model driven form
  public payLoad: string;

    public onSubmit() {
        this.payLoad = JSON.stringify(this.myForm.value);
    }

  constructor(private compiler: Compiler,private formBuilder: FormBuilder,private sanitizer: DomSanitizer) {}

ngOnInit() {
      this.myForm = this.formBuilder.group({
            name: ['', [<any>Validators.required, <any>Validators.minLength(5)]],
            lastname: ['', [<any>Validators.required, <any>Validators.minLength(5)]],
            address: ['', [<any>Validators.required, <any>Validators.minLength(5)]]
            });
}
  ngAfterViewInit() {

    this.addComponent('<div  class="form-row"> <label for="">Address</label> <input type="text" class="form-control" formControlName="address">  </div>');
  }

  private addComponent(template: string) {
    @Component({template: template})
    class TemplateComponent {}

    @NgModule({declarations: [TemplateComponent]})
    class TemplateModule {}

    const mod = this.compiler.compileModuleAndAllComponentsSync(TemplateModule);
    const factory = mod.componentFactories.find((comp) =>
      comp.componentType === TemplateComponent
    );
    const component = this.container.createComponent(factory);
  }
}

Plunker 不起作用,所以我在 stackbliz 中添加了示例。

https://stackblitz.com/edit/angular-t3mmg6

此示例是动态表单控件,位于添加组件中(您可以在此处从服务器获取表单控件)。如果您看到 addcomponent 方法,您可以看到表单控件。在这个例子中,我没有使用 Angular Material ,但它有效(我正在使用@work)。这是针对 Angular 6 的,但适用于所有以前的版本。

需要为 AngularVersion 5 及以上版本添加 JITComplierFactory。

谢谢

维杰

最佳答案

问题是您将组地址添加到父组件中的表单构建器组中,但 html 作为子组件添加,无法更新您的表单组值。

使用父子方式,当值发生变化时,需要将值的变化从子组件输出到父组件,然后手动设置表单组的值,看看这里有一些不同的方式父子组件之间的通信:https://angular.io/docs/ts/latest/cookbook/component-communication.html

对我来说,如果您可以使用 ngFor 或 ngIf 指令来控制动态表单而不是添加子组件,那么看起来会更容易。请查看此处,了解如何执行此操作的示例:https://angular.io/docs/ts/latest/cookbook/dynamic-form.html

关于angular - 如何从动态 HTML 中获取表单值 Angular2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40983654/

相关文章:

node.js - Web 应用程序(API 和前端)- 路由设计

javascript - html 元素属性和脚本值之间的数据绑定(bind)不同步

Angular2 空响应处理

node.js - 在 TypeScript 中导入 Node 模块

javascript - 仅与 TypeScript 类型相关的属性?

angular - 使用 ASP.Net Core MVC 和 ASP.Net Web Api 在 Angular2 App 中进行 HTML5 路由

javascript - Angular ngrx例子理解reselect

javascript - 如何让 Angular 在 ajax get 之后更新集合

Angular 通用 : How to create an app shell and only pre-render the shell?

typescript - 如何防止 TypeScript 中断基于 Webpack 的 ProvidePlugin 上声明的未解析变量的 Webpack 构建?