angular6 - 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);
}
}
解决方案
在您的子组件中将输入定义为:
import { Input} from '@angular/core';
@Input() some_variable_name: Object;
现在在您的父组件中将您的对象传递为:
<child-component [some_variable_name] = "object_variable" />
查看官方文档了解更多详情:https ://angular.io/guide/component-interaction
推荐阅读
- r - R:将字符串合并为一个公式对象
- android - onTouch() 方法显示没有使用
- django - django数据库数据删除和备份
- r - 如何检查变量元组是否导致第二个元组列表中的匹配?
- javascript - JS:使用 && 条件代替 if 是否有优化影响
- javascript - onMouseEnter 在 antd 表的一个单元格上
- c# - Object 但不是派生类的扩展方法
- json - 数据未通过 mqtt 从 nodered 传输到 thingsboard
- javascript - 由 Glassfish 提供时,javascript 中的 utf-8 文本无法正确显示
- ngrx - 组件中的 NGRX 实体测试