Home > Enterprise >  getting input from child of child component in angular
getting input from child of child component in angular

Time:08-25

need some clarification on detecting the changes in a child of the child component for example, I have a parent component that contains a button to submit and inside the parent component, I have a child-1 component inside the child-1 component, I have the child-2 component containing forms once the button is clicked from the parent component I need to get the form value from the child-2 component to the parent component whenever the input changed

any solution?

enter image description here

CodePudding user response:

You can use the @Input & @Output decorators to pass in data to your child components. Check this StackBlitz out for a quick demo.

https://stackblitz.com/edit/angular-ivy-f23te8

CodePudding user response:

I am using a different approach, where we move the variable needed to submit the form inside a service and then calling the submit method from the root comment.

child ts

import { Component, Input, ViewChild } from '@angular/core';
import {
  FormGroup,
  FormControl,
  FormBuilder,
  Validators,
} from '@angular/forms';
import { FormService } from '../../form.service';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'my-form-child',
  templateUrl: './my-form-child.component.html',
})
export class MyFormChildComponent {
  myFormFather: FormGroup;
  @ViewChild('form') form: NgForm;

  constructor(private fb: FormBuilder, private formService: FormService) {}

  ngOnInit() {
    this.createForm();
  }

  ngAfterViewInit() {
    this.formService.form = this.form;
  }

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

  onSubmit() {
    alert('submitted');
  }
}

child html

<form [formGroup]="myFormFather" (ngSubmit)="onSubmit()" #form="ngForm">
  Nickname: <input formControlName="nickName" /><br />
  Name: <input formControlName="name" /><br />
  Age: <input formControlName="age" />
  <button type="submit" [disabled]="myFormFather.invalid">Save</button>
</form>

<div>
  {{ myFormFather.value | json }}
</div>

parent ts

import { Component } from '@angular/core';
import { FormService } from './form.service';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular 5';

  constructor(private formService: FormService) {}

  get form(): NgForm {
    return this.formService.form;
  }
}

parent html

<button (click)="form && form.ngSubmit && form.ngSubmit.emit()" type="submit">
  external submit
</button>

<my-form-father></my-form-father>

forked stackblitz

  • Related