【问题标题】:How to pass object from one component from other component using angular6如何使用角度 6 从一个组件从另一个组件传递对象
【发布时间】:2019-07-09 10:42:26
【问题描述】:

我是 Angular 的新手。我正在创建表单,提交表单后,我将在对象中获取数据。我需要将该对象传递给另一个组件,是否可以使用 @Input 属性。如果是,我们如何通过使用 @Input 属性来实现这一点。请帮帮我。

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


    【解决方案1】:

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

    import { Input} from '@angular/core';
    
     @Input() some_variable_name: Object;
    

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

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

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

    【讨论】:

    • 我在子组件中获取对象未定义。我已经更新了我的代码。请检查我的代码。
    • 您已经在 onSubmit 函数中本地定义了 FormObject。像parentObject 一样在全局范围内定义它。你也不需要在父组件中定义parentObject
    猜你喜欢
    • 2019-10-27
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    • 2020-03-28
    • 2017-05-28
    相关资源
    最近更新 更多