簡體   English   中英

Angular中具有組件子的反應形式

[英]reactive form with component child in Angular

正如您所看到的,我有一個父組件組件與組件子組件。 {{myFormFather.value}}顯示nickName值和name值,但不顯示age值。 {{myFormFather.status}}它不識別組件子。 就像我的孩子是幻影一樣,為什么?

我的外形father.html

<form [formGroup]="myFormFather" (ngSubmit)="onSubmit()">
    <input formControlName="nickName">
    <input formControlName="name">
    <my-form-child
            [age]="myFormFather">
    </my-form-child>
    <button type="submit"
            [disabled]="myFormFather.invalid">Save
    </button>
</form>

我的外形father.ts

myFormFather = new FormGroup({
    nickName: new FormControl(),
    name: new FormControl()
});

constructor(private fb:FormBuilder) {}

ngOnInit() {this.createForm()}

createForm() {
    this.myFormFather = this.fb.group({
        nickName: ['', [Validators.required],
        name: ['', [Validators.required]
    });
}

我的外形child.html

<div [formGroup]="ageForm">
    <input formControlName="age">
</div>

我的外形child.ts

@Input() ageForm = new FormGroup({
    age: new FormControl()
});

constructor(private fb:FormBuilder) {}

ngOnInit() {this.createForm()}

createForm() {
    this.ageForm = this.fb.group({
        age: ['', [Validators.required]]
    });
}

嗨,你一直在尋找的解決方案

演示堆閃電戰

問題是:您覆蓋了從父級傳遞的表單組

@Input() ageForm = new FormGroup({
  age: new FormControl()
});

constructor(private fb: FormBuilder) {}

ngOnInit() {
  this.createForm()
}

createForm() {
  // This is overwriting the FormGroup passed from parent!
  this.ageForm = this.fb.group({
    age: ['', [Validators.required]]
  });

  // Instead you had to use
  // this.ageForm.addControl("age", new FormControl('', Validators.required));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM