如何通过@Input实现Angular父组件表单数据传递至子组件展示
解决Angular父组件表单数据通过@Input传递给子组件展示的问题
你的代码存在几个关键问题,以下是针对性的修复方案:
1. 修正父组件模板结构与表单提交逻辑
Angular组件模板无需包含<html>、<head>、<body>标签(这些属于根index.html);同时你当前通过routerLink跳转到新路由的方式会断开父子组件层级关系,@Input仅适用于同一视图内的父子组件。
修复后的 loginform.html
<div class="form"> <h2 id="registration">Login Form</h2> <form (ngSubmit)="navToDisplayForm()" #f="ngForm"> <div> <label for="firstname">First Name</label> <input type="text" id="firstname" placeholder="Your name.." name="firstname" [(ngModel)]='userModel.firstnamedetail' required> <label for="middlename">Middle Name</label> <br> <input type="text" id="middlename" placeholder="Your middlename.." name="middlename" [(ngModel)]='userModel.middlenamedetail' required> <br> <label for="lastname">Last Name</label> <input type="text" id="lastname" placeholder="Your lastname.." name="lastname" [(ngModel)]='userModel.lastnamedetail' required> </div> <br><br> <button class="btn btn-info" type="submit" value="Submit" id="btn">Submit</button> <p>Not Registered? <span>Create Account</span></p> </form> </div> <!-- 条件显示子组件,仅在提交后展示 --> <app-userdata *ngIf="showChild" [childData]="sendToChild"></app-userdata>
修复后的 loginform.ts
添加状态控制子组件显示,并优化数据传递逻辑:
import { Component, OnInit } from '@angular/core'; import { NgForm } from "@angular/forms"; @Component({ selector: 'app-loginform', templateUrl: './loginform.component.html', styleUrls: ['./loginform.component.css'] }) export class LoginformComponent implements OnInit { userModel = { firstnamedetail: '', middlenamedetail: '', lastnamedetail: '' }; sendToChild: any; showChild = false; // 控制子组件显示状态 constructor() { } ngOnInit(): void { } navToDisplayForm() { // 深拷贝避免后续输入修改影响已传递的数据 this.sendToChild = {...this.userModel}; this.showChild = true; // 显示子组件 } }
2. 修正子组件数据接收与展示
子组件模板使用的属性名与父组件传递的userModel不匹配,同时无需保留路由相关代码(因为不再跳转路由)。
修复后的 userdata.ts
import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-userdata', templateUrl: './userdata.component.html', styleUrls: ['./userdata.component.css'] }) export class UserdataComponent implements OnInit { constructor() { } // 直接接收父组件传递的userModel结构数据 @Input() childData: any; ngOnInit(): void { } }
修复后的 userdata.html
使用与父组件userModel一致的属性名:
<div> <form class="display"> <p>First Name: {{childData.firstnamedetail}}</p> <p>Middle Name: {{childData.middlenamedetail}}</p> <p>Last Name: {{childData.lastnamedetail}}</p> </form> </div>
关键修复点说明
- 移除路由跳转:
@Input依赖父子组件在同一视图层级,跳转路由会创建新组件实例,无法通过@Input传递数据。 - 属性名匹配:确保子组件模板使用的属性名与父组件传递的数据结构一致。
- 条件显示子组件:通过
*ngIf控制子组件在表单提交后才显示,避免初始状态下的空值渲染。 - 深拷贝数据:使用
{...this.userModel}进行深拷贝,防止后续父组件输入框修改影响已传递给子组件的数据。
内容的提问来源于stack exchange,提问作者Tinku
相关产品推荐
相关产品推荐

