【问题标题】:Dynamic forms singleton?动态表单单例?
【发布时间】:2019-06-14 01:20:11
【问题描述】:

我正在尝试以角度理解动态表单部分,但我不确定我是否理解正确。

例如:我用表单控件构建了一个表单组,并通过输入将其发送到另一个组件。

动态表单组件.html:

<div>
    <form (ngSubmit)="onSubmit()" [formGroup]="form">
        <div *ngFor="let question of questions" class="form-row">
            <app-question [question]="question" [form]="form"></app-question>
        </div>

        <div class="form-row">
            <button type="submit" [disabled]="!form.valid">Save</button>
        </div>
    </form>

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

动态表单.component.ts:

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

在 app-question 组件中,此表单将被更改,我的意思是字段将填充用户选择的数据选项。

当他完成后,用户将按下“保存”数据是如何更新的?我的意思是我不需要将值发送回父组件? (从 app-question > dynamic-form 发送新的表单数据)表单是单例服务吗?那么子组件内部的每一次更改,都会在父窗体中进行更改吗?

【问题讨论】:

    标签: angular forms dynamic angular7


    【解决方案1】:

    罗伯托,当你使用@Input,并且输入是一个对象时,你不需要使用输出,因为你传递了一个对象的“引用”。

    一个愚蠢的例子

    父母

    @Component({
      selector: 'my-app',
      template: `
      <child [object]="object"></child>
      {{object|json}}` //<--after 1 seconds you can see { "property1": 1, "property2": 3 }
    })
    export class AppComponent {
      object={property1:1,property2:2}
    }
    

    孩子

    @Component({
      selector: 'child',
      template: `child`
    })
    export class HelloComponent implements OnInit  {
      @Input() name: any;
      ngOnInit()
      {
         setTimeout(()=>{
            this.name.property2=3
         },1000)
      }
    }
    

    将 app-question 传递为 @Input "form" 和 "question"。这是因为应用程序上的更改改变了表单:它是同一个控件! (不是因为 form 有点像“singelton”)

    【讨论】:

      猜你喜欢
      • 2011-09-03
      • 1970-01-01
      • 2018-05-26
      • 1970-01-01
      • 2023-03-02
      • 1970-01-01
      • 2021-04-30
      • 2012-11-05
      • 2014-03-22
      相关资源
      最近更新 更多