Angular中使用@Input获取属性值始终为undefined的问题求助
问题分析
你的核心问题是错误理解了@Input装饰器的使用场景:@Input是用来接收父组件传递给当前子组件的属性值,而你现在把[miName]绑定在了当前组件模板内的ion-input元素上,这完全不符合@Input的设计逻辑,所以this.miName始终返回undefined。
解决方案
根据你的需求(输入框有内容时发送输入值,为空时发送预设值),分两种场景给出实现:
场景1:预设值是当前组件内部固定值
不需要使用@Input,直接在组件内定义默认值,提交时判断即可:
修改后的组件代码
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-ficha-ub', templateUrl: './ficha-ub.page.html', styleUrls: ['./ficha-ub.page.scss'], }) export class FichaUbPage implements OnInit { id: any; nombre!: string; // 定义内部默认值 private defaultName = 'hola'; constructor(private activatedRoute: ActivatedRoute, private http: HttpClient) { } ngOnInit() { // 可选:初始化时把默认值赋值给输入框,让用户看到 // this.nombre = this.defaultName; } envDatos(){ // 判断输入框内容,为空则使用默认值 const sendValue = this.nombre?.trim() || this.defaultName; console.log('要发送的值:', sendValue); } }
模板代码(去掉错误的[miName]绑定)
<ion-input type="text" placeholder="{{dat.nombre}}" label="" [(ngModel)]="nombre"></ion-input> <div class="btnSmt"> <ion-button class="btn1 color-primary-btn" (click)="envDatos()">Actualizar Datos</ion-button> </div>
场景2:预设值需要从父组件传递
如果预设值hola是需要父组件提供的,才需要用@Input,正确用法如下:
父组件模板(使用子组件时绑定属性)
假设父组件模板中引用了你的app-ficha-ub组件:
<app-ficha-ub [miName]="'hola'"></app-ficha-ub>
子组件代码(保留@Input,修改提交逻辑)
import { Component, Input, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-ficha-ub', templateUrl: './ficha-ub.page.html', styleUrls: ['./ficha-ub.page.scss'], }) export class FichaUbPage implements OnInit { id: any; nombre!: string; @Input() miName!: string; constructor(private activatedRoute: ActivatedRoute, private http: HttpClient) { } ngOnInit() { // 可选:初始化时把父组件传递的默认值赋值给输入框 // this.nombre = this.miName; } envDatos(){ const sendValue = this.nombre?.trim() || this.miName; console.log('要发送的值:', sendValue); } }
子组件模板(去掉ion-input上的[miName]绑定)
<ion-input type="text" placeholder="{{dat.nombre}}" label="" [(ngModel)]="nombre"></ion-input> <div class="btnSmt"> <ion-button class="btn1 color-primary-btn" (click)="envDatos()">Actualizar Datos</ion-button> </div>
关键提醒
- @Input的作用是父子组件间的传值,只能在父组件引用子组件时绑定到子组件标签上,不能绑定到子组件内部的DOM元素上。
- 若需要响应父组件传入值的更新,可以使用
ngOnChanges生命周期钩子监听@Input值的变化。
内容的提问来源于stack exchange,提问作者Violeta Quintanilla
相关产品推荐
相关产品推荐

