首页 > 解决方案 > 动态表单单例?

问题描述

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

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

动态表单组件.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>

动态form.component.ts:

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

在应用程序问题组件中,此表单将被更改,我的意思是字段将填充用户选择的数据选项。

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

标签: angularformsdynamicangular7

解决方案


罗伯托,当您使用 @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“表单”和“问题”。这是因为应用程序上的更改改变了表单:它是同一个控件!(不是因为形式有点像“singelton”)


推荐阅读