Angular/Ionic父子组件@Input属性绑定失败问题求助
Hey there! Let's walk through why your parent-to-child @Input binding isn't working, and fix it step by step based on the code you shared.
1. You're Missing the @Input Declaration in the Child Component
This is the most common culprit! Your parent HomePage has the oneObject ready to pass, but your NewComponent hasn't told Angular it accepts this input.
Update your new.ts file to include the @Input() decorator:
import { Component, Input } from '@angular/core'; @Component({ selector: 'new-component', // Double-check this matches what you use in home.html templateUrl: 'new.html' }) export class NewComponent { // Declare the input property to receive data from the parent @Input() oneObject: { content: string }; }
2. Correctly Use the Child Component in Parent's Template
Your home.html code was cut off, but you need to add the child component's selector and bind the oneObject property to it. Here's how to complete it:
<ion-header> <ion-navbar> <ion-title>Ionic Blank</ion-title> </ion-navbar> </ion-header> <ion-content padding> <!-- Use the child component's selector, and bind the property with [] --> <new-component [oneObject]="oneObject"></new-component> </ion-content>
Important: Make sure the selector <new-component> exactly matches the selector value in your NewComponent's @Component decorator.
3. Ensure the Child Component is Declared in Your Module
Angular won't recognize your child component unless it's added to the declarations array of your module (either app.module.ts or a feature module like HomeModule):
import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { HomePage } from './home'; import { NewComponent } from '../../components/new/new'; @NgModule({ declarations: [ HomePage, NewComponent // Add your child component here ], imports: [ IonicPageModule.forChild(HomePage) ] }) export class HomePageModule {}
4. Safely Use the Input in the Child's Template
In your new.html, use the input property to display the content. Add the safe navigation operator ?. to avoid errors while the data loads:
<div class="card-content"> {{ oneObject?.content }} </div>
After checking all these steps, your parent-to-child binding should work as expected!
内容的提问来源于stack exchange,提问作者user4422315

