angular - 动态表单单例?
问题描述
我正在尝试以角度理解动态表单部分,但我不确定我是否理解正确。
例如:我用表单控件构建了一个表单组,并通过输入将其发送到另一个组件。
动态表单组件.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 发送新的表单数据)表单是单例服务吗?那么子组件内部的每一次更改,都会在父窗体中进行更改吗?
解决方案
罗伯托,当您使用 @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”)
推荐阅读
- ios - 如何从 SwiftUI 视图使用后退按钮推送到 UIKit ViewController
- python-3.x - PySide2 / QLayout:无法向 QHBoxLayout 添加空布局
- excel - 将 Excel 拆分为单独的文件夹,然后在每个文件夹中都有文件。文件夹和文件都与工作表命名相同
- java - 将小于 controlValue 的任何元素的值加倍。例如:如果 controlValue = 10,则 dataPoints = {2, 12, 9, 20} 变为 {4, 12, 18, 20}
- php - 如何在 FPDF 中使用 Open-type SVG 字体文件的默认字体颜色?
- java - 网络答案的单元测试
- javascript - 比较 JS 中的两个数组的线性时间复杂度
- git - 将更改应用于现有提交而无需交互式变基
- windows - 如何在 Windows 中提取远程 git 存储库的最新提交哈希?
- javascript - Apollo Server:如何从 REST API 数据源访问 Dataloader 中解析器之外的“上下文”