gpt4 book ai didi

javascript - 如何从子组件中获取父表单的字段?

转载 作者:行者123 更新时间:2023-12-02 22:02:42 28 4
gpt4 key购买 nike

我有以下结构:

父组件(对话框)

<form #dialogForm="ngForm">
<app-window-element></app-window-element>
</form>
<button (click)="button.callback(dialogForm)">Click me</button>

子组件(元素)

<div>
<label for="email">Email</label>
<input type="text" name="email" id="email" formControlName="email">

<label for="password">Password</label>
<input type="password" name="password" id="password" formControlName="password">
</div>

当点击按钮时 - 发送#dialogForm

但我有问题 - 对象 dialogForm 没有子组件中的字段。 (dialogForm 是 NgForm)

我收到错误:

WindowFormComponent.html:5 ERROR Error: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class).

Example:

<div [formGroup]="myGroup">
<input formControlName="firstName">
</div>

In your class:

this.myGroup = new FormGroup({
firstName: new FormControl()
});

如果我在表单中只有字段 - 它是有效的,但不适用于子组件。

<form #dialogForm="ngForm">
<label for="email">Email</label>
<input type="text" name="email" id="email" formControlName="email">

<label for="password">Password</label>
<input type="password" name="password" id="password" formControlName="password">
</form>
<button (click)="button.callback(dialogForm)">Click me</button>

最佳答案

您可以将整个表格传递给您的 child ,如下所示:

parents.ts

constructor(fb: FormBuilder) {
this.myGroup = fb.group({
email: new FormControl(''),
password: new FormControl('')
});
}

onSubmit() {
console.log(this.myGroup.value);
}
parents.html

<form [formGroup]="myGroup" (ngSubmit)="onSubmit()">
<app-window-element [parentform]="myGroup"></app-window-element>
<button></button>
</form>
child.ts

@Input() parentForm: FormGroup;
child.html

<div [formGroup]="parentForm">
<label for="email">Email</label>
<input type="text" name="email" id="email" formControlName="email">

<label for="password">Password</label>
<input type="password" name="password" id="password" formControlName="password">
</div>

关于javascript - 如何从子组件中获取父表单的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59824997/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com