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

Angular中如何通过子组件操作获取动态子输入组件的值?

如何在Angular中获取动态生成的子组件输入值

问题场景

父组件包含ButtonComponent和根据数组动态生成的InputComponent,点击ButtonComponent中的按钮时,需要收集所有InputComponent的输入值。目前已实现按钮点击事件从ButtonComponent传递到父组件,但不清楚如何获取所有输入框的值。


现有代码实现

AppComponent

app.component.ts

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;

  ids = ['a1', 'b1', 'c1', 'd1', 'g1'] // 此数组为动态生成

  onSaved(){
    // 如何在这里获取所有输入值?
    console.log('saved clicked')
  }
}

app.component.html

<app-button-component (saved)="onSaved()"></app-button-component>
<app-input-component *ngFor="let id of ids" [id]='id'></app-input-component>

ButtonComponent

button-component.component.ts

export class ButtonComponentComponent implements OnInit {

  @Output() saved = new EventEmitter()

  constructor() { }

  ngOnInit() {
  }

  save(){
    this.saved.emit('true')
  }

}

button-component.component.html

<button (click)="save()" >Save</button>

InputComponent

input-component.component.ts

export class InputComponentComponent implements OnInit {

  @Input() id =''
  constructor() { }

  ngOnInit() {
  }

}

input-component.component.html

<div class="inp">
  <span>{{id}}</span>
  <input type="number" min="1" max="100" />
</div>

解决方案

方法一:通过ViewChildren获取子组件实例

这种方法需要先改造InputComponent,让它暴露输入值的访问接口:

  1. 改造InputComponent,添加输入框双向绑定和值获取方法:
// input-component.component.ts
import { Component, Input, OnInit } from '@angular/core';

export class InputComponentComponent implements OnInit {
  @Input() id = '';
  inputValue: number | null = null; // 绑定输入框的值

  constructor() { }

  ngOnInit() {
  }

  // 返回当前输入框的id和值
  getInputData(): { id: string; value: number | null } {
    return { id: this.id, value: this.inputValue };
  }
}

对应的HTML修改为双向绑定(需确保模块导入FormsModule):

<!-- input-component.component.html -->
<div class="inp">
  <span>{{id}}</span>
  <input type="number" min="1" max="100" [(ngModel)]="inputValue" />
</div>
  1. 父组件中通过ViewChildren获取所有子组件实例并收集值:
// app.component.ts
import { Component, ViewChildren, QueryList } from '@angular/core';
import { InputComponentComponent } from './input-component/input-component.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;
  ids = ['a1', 'b1', 'c1', 'd1', 'g1'];

  // 声明QueryList存储所有InputComponent实例
  @ViewChildren(InputComponentComponent) inputComponents!: QueryList<InputComponentComponent>;

  onSaved(){
    // 遍历子组件收集所有输入值
    const allInputValues = this.inputComponents.map(comp => comp.getInputData());
    console.log('所有输入值:', allInputValues);
  }
}

方法二:通过双向绑定同步到父组件数组

这种方法让父组件直接维护输入值数组,无需额外获取子组件实例:

  1. 改造InputComponent,实现自定义双向绑定:
// input-component.component.ts
import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';

export class InputComponentComponent implements OnInit {
  @Input() id = '';
  @Input() inputValue: number | null = null;
  @Output() inputValueChange = new EventEmitter<number | null>();

  constructor() { }

  ngOnInit() {
  }

  // 输入值变化时通知父组件
  handleInputChange(event: Event) {
    const target = event.target as HTMLInputElement;
    const newValue = target.value ? +target.value : null;
    this.inputValueChange.emit(newValue);
  }
}

对应的HTML修改:

<!-- input-component.component.html -->
<div class="inp">
  <span>{{id}}</span>
  <input 
    type="number" 
    min="1" max="100" 
    [value]="inputValue" 
    (input)="handleInputChange($event)" 
  />
</div>
  1. 父组件初始化输入值数组并绑定到子组件:
// app.component.ts
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;
  ids = ['a1', 'b1', 'c1', 'd1', 'g1'];
  // 初始化与ids对应的输入值数组
  inputValues: { id: string; value: number | null }[] = this.ids.map(id => ({ id, value: null }));

  onSaved(){
    console.log('所有输入值:', this.inputValues);
  }
}

父组件HTML修改为双向绑定:

<!-- app.component.html -->
<app-button-component (saved)="onSaved()"></app-button-component>
<app-input-component 
  *ngFor="let item of inputValues; let i = index" 
  [id]="item.id" 
  [(inputValue)]="item.value"
></app-input-component>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 00:35:43