【问题标题】:Get child component form value in parent component's form submission?在父组件的表单提交中获取子组件的表单值?
【发布时间】:2017-11-01 01:19:41
【问题描述】:

注意:由于problem is a little complex,代码被抽象为可读性

我们有一个像这样的<child-component> 组件模板:

<select name="someName" #someID ngDefaultControl [(ngModel)]="someModel" (ngModelChange)="onChange(someID.value)">
      <option *ngFor="let a of list" [ngValue]="a.key">{{a.value}}</option>
</select>

ts 文件与output 配置:

@Component({
  moduleId: module.id,
  selector: 'child-component',
  templateUrl: 'child-component.html',
  outputs: ['someChildEvent']
})

export class ChildComponent {
  someChildEvent = new EventEmitter<string>();
  onChange(value) {
    this.someChildEvent.emit(value);
  }
}

我们这样调用&lt;parent-component&gt;

<form #f="ngForm" (submit)="submit(f)" >
<child-component (childEvent)="childData=$event"></child-component>
<input type="submit" value="submit">
</form>

.ts 类似:

export class ParentComponent {
    childData;

    submit(f) {
        //How to access childData here?
    }
}
  • 它是 Angular 2 中 output configuration 的正确实现吗?
  • 我们如何从&lt;parent-component&gt;form提交到submit(f)函数的&lt;child-component&gt;访问selectoption的值?

【问题讨论】:

  • childEvent 必须是 someChildEvent
  • @echonax 绝对正确,但是我们如何在submit(f) 函数中获取&lt;child-component&gt;select 元素的值?
  • 那可能是因为[ngValue]="a.key" 所以a.key0 我猜?它会使用[ngValue]="a" 发送整个对象
  • 只是一个建议,不要在@Component 注释中使用outputs 属性,而是在someChildEvent 属性上使用@Output 注释,如下所示:@Output() someChildEvent = new EventEmitter&lt;string&gt;();
  • 它将使您的代码更具可读性和可维护性。例如,如果重构 someChildEvent 属性的名称,则无需更新 outputs 中无法进行类型检查的字符串数组。

标签: javascript angular typescript output


【解决方案1】:
<child-component (childEvent)="childData=$event"></child-component> 

此处的事件名称需要与您的方法名称匹配,因此应该是:

<child-component (someChildEvent)="childData=$event"></child-component>

如果您想发送在选择框中选择的对象,请将 ngValue 更改为该对象并相应地更改模型事件:

[ngValue]="a"

(ngModelChange)="onChange($event)"

【讨论】:

  • @xameeramir 很高兴我能帮上忙 :-)
猜你喜欢
  • 2021-09-29
  • 2016-06-25
  • 2019-03-07
  • 2019-09-27
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多