首页 > 解决方案 > How to pass object from one component from other component using angular6

问题描述

I am new to angular. I am creating form, and after submitting form, I will get data in object. I need to pass that object to the other component, is it possible by using @Input property. If Yes how can we achieve that by using @Input property. Please help me.

parent.component.html

    <form [formGroup]="addForm" (ngSubmit)="onSubmit()">
      Name: <input type="text" formControlName="name" placeholder="Name"><br/>
     Fname: <input type="text" formControlName="fname" placeholder="FirstNAme"><br/>
     Lname: <input type="text" formControlName="lname" placeholder="LastName"><br/>
    <button>Submit</button>
      </form>

<h1>Hello {{message}}</h1> <br/> 

  <app-forms [parentObject]="FormObject">]</app-forms>

parent.component.ts

import { Component, OnInit,Input } from '@angular/core';
import { FormGroup ,FormBuilder } from '@angular/forms';
import {Router} from "@angular/router";

@Component({
  selector: 'app-form1',
  templateUrl: './form1.component.html',
  styleUrls: ['./form1.component.css']
})
export class Form1Component implements OnInit {

  addForm:FormGroup;

  parentObject:Object;

  constructor(private fb:FormBuilder, private router: Router) { }

  ngOnInit() {
this.addForm=this.fb.group({
  name:[''],
  fname:[''],
  lname:['']

})
  }

  onSubmit(){
    console.log(this.addForm.value);
    var  FormObject=this.addForm.value
  }

}

child.component.ts

import { Component, OnInit,Input } from '@angular/core';

@Component({
  selector: 'app-forms',
  templateUrl: './forms.component.html',
  styleUrls: ['./forms.component.css']
})
export class FormsComponent implements OnInit {
  @Input() parentObject: Object;
 constructor() { }


  ngOnInit() {
    console.log(this.parentObject);
  }

}

标签: angular6

解决方案


在您的子组件中将输入定义为:

import { Input} from '@angular/core';

 @Input() some_variable_name: Object;

现在在您的父组件中将您的对象传递为:

<child-component [some_variable_name] = "object_variable" />

查看官方文档了解更多详情:https ://angular.io/guide/component-interaction


推荐阅读