相关疑难解决方法(0)

Angular:如何访问嵌套表单中控件的值

我正在尝试在控制台和 HTML 中打印获取嵌套表单的表单控件的值。

userForm = new FormGroup({
    name: new FormControl("Tom Alter"),
    address: new FormGroup({
        Country: new FormControl("India"),
        State: new FormControl("Delhi")
    })
});
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,我都可以使用 get 语句找到值。

console.log ("name : ", this.userForm.controls.name.value);
console.log ("Country using Get Way 1  : ", this.userForm.get(['address', 'Country']).value) ;
console.log ("Country using Get Way 2 : ", this.userForm.get(['address']).get(['Country']).value);
console.log ("Country using Get Way 3 : ", this.userForm.get(['address.Country']).value);
console.log ("Country without Get: ", this.userForm.group.address.controls.cCountry.value);
Run Code Online (Sandbox Code Playgroud)

在这些“名称”中,“Way1”、“Way2”正在工作,但是“Way 3”和“Without get”不起作用,因为它适用于“name”

同样在 HTML 中:

Name : {{userForm.controls.name.value}}
<br>
<br>
Country with get Way …
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms

2
推荐指数
1
解决办法
2481
查看次数

带有子表单组件的 Angular 父表单,如何让子表单知道父表单已提交?

我正在以这种方式使用父表单和子组件表单。/sf/answers/4151721101/

当父表单提交了按钮 Ng 时,如何让子组件知道?ParentForm 变量在子组件中作为变量。有没有办法,我可以将parentFormGroup 作为一个事件来告诉我?

当子窗体知道时,我想计算一些复杂的值(不在窗体中),并将它们发送到父组件。

父组件:

 ngOnInit() {
    this.parentForm = this.fb.group({
       'customerName': [null, [Validators.required]],
       'phoneNumber': [null, [Validators.required]],
    })

 <form [formGroup]="parentForm" (ngSubmit)="onSubmit()">
    <app-child [form]="parentForm"></app-child>
    <button type="submit">Purchase</button>
 </form>
Run Code Online (Sandbox Code Playgroud)

子组件:

需要知道在这个组件中,parentForm 是什么时候提交的。

@Input() parentForm: FormGroup;

ngOnInit() {
    this.parentForm.addControl('address', new FormControl(Validators.required));
    this.parentForm.addControl('city', new FormControl(Validators.required));
 }
Run Code Online (Sandbox Code Playgroud)

typescript angular angular-reactive-forms angular11

1
推荐指数
1
解决办法
5879
查看次数