You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular子组件表单无法加载父组件数据并设为不可编辑

问题解决:Angular输入框无法预填充父组件传入值且设置不可编辑

问题原因

你定义userData时直接赋值this.triggerID,但此时组件刚完成初始化,@Input的triggerID还未从父组件接收数据,导致userData.triggerID初始为undefined。后续父组件传入值后,triggerID更新但userData未同步,所以输入框为空。

解决方案

1. 同步userData与triggerID的值

将userData的赋值逻辑移到ngOnInit钩子中执行,因为ngOnInit触发时,@Input属性已完成赋值:

修改后的triggerform.component.ts:

import { Component, Input, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-triggerform',
  templateUrl: './triggerform.component.html',
  styleUrls: ['./triggerform.component.css'],
})
export class TriggerformComponent implements OnInit {
  @Input() parentEmailID!: string;
  @Input() triggerID!: any;
  @Input() triggerAssignedTo!: string;
  @Input() isActive!: boolean;
  
  userData = {
    triggerID: undefined
  };

  constructor() {}

  ngOnInit(): void {
    this.userData.triggerID = this.triggerID;
  }
}

如果父组件会动态更新triggerID,可以通过setter实现实时同步:

private _triggerID!: any;
@Input() set triggerID(value: any) {
  this._triggerID = value;
  this.userData.triggerID = value;
}
get triggerID(): any {
  return this._triggerID;
}

2. 设置输入框不可编辑

根据需求选择readonly或disabled属性:

  • readonly:输入框不可编辑,值会随表单提交
  • disabled:输入框不可编辑,值不会随表单提交

修改后的triggerform.component.html:

{{triggerID}}<!-- shows the fetched value -->
<form #userForm="ngForm">
<input type="text" name="triggerID" [(ngModel)]="userData.triggerID" readonly><br><br>
<button type="submit">Submit Changes</button>
</form>

内容的提问来源于stack exchange,提问作者hawker_Baker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 17:55:29