Pass Angular Reactive FormControls to Children Components

后端 未结 1 1200
迷失自我
迷失自我 2020-12-19 01:15

I have a parent component where I want to create and store my Reactive Form. There will be multiple Form Group instances in a Form Array. I want to pass the Form Controls fr

1条回答
  •  悲哀的现实
    2020-12-19 01:27

    It's not too tough, once you know what to look for. If you have never done it before, it can be a challenge. The error messages you get don't always help.

    First, you want to add some things to your DetailsFields component. The new Inputs will allow you to pass in the instance of the form group you constructed in your parent component. The car and carIndex inputs will be used to pass in the values the child component will need in order to work like you have them now.

    import { Component, OnInit, Input } from '@angular/core';
    import { FormGroup } from '@angular/forms';
    
    @Component({
        selector: 'app-child',
        templateUrl: './details-fields.component.html',
        styleUrls: ['./details-fields.component.css']
    })
    
    export class DetailsFields implements OnInit {
        @Input() form: FormGroup;
        @Input() car: any;
        @Input() carIndex: number;
    
        ngOnInit() { }
    }
    

    Second, you want to move some of the template HTML you have in you parent component to the child component. The child component template (details-fields.component.html) will look like this in the end. The [formGroup]="form" in the first div is the real key here. That is what tells the child template what form group to use. You pass this from the parent in the code after this.

    This car is a {{car.make}}

    The parent component template will be only left with this. This is where you pass the carsForm form group to the child component, along with the car and the carIndex.

    The last thing I did was move the styles you had in the parent component out to the styles.css file, so all components could use them.

    That's it! Really just moving some code around and adding some inputs so you can pass the child what it needs.

    0 讨论(0)
提交回复
热议问题