javascript - 在父组件的表单提交中获取子组件表单值?

标签 javascript angular typescript output

Note: since the problem is a little complex, the code is abstracted for readability

我们有一个 <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);
  }
}

我们在 <parent-component> 中调用像这样:

<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?
    }
}
  • 它是 output configuration 的正确实现吗?在 Angular 2 中?
  • 我们如何访问 select 的值的 option来自 <child-component><parent-component>form提交给submit(f)功能?

最佳答案

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

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

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

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

[ngValue]="a"

(ngModelChange)="onChange($event)"

关于javascript - 在父组件的表单提交中获取子组件表单值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44281328/

相关文章:

javascript - javascript中以一定速度跟随鼠标光标的图像

angular - rxjs switchMap 在 Angular Guard 中不起作用?

css - Chrome 和 IE 之间的 Angular Material 下拉列表不同

javascript - Angular2 中两个组件干扰文件事件

javascript - TypeScript 中定义的对象字面量键的类型是什么?

javascript - Push() 无法显示字符串

javascript - 如何在tinymce文本区域中输入字符时将字符附加到文本框,直到按ENTER键?

javascript - 悬停图像上的颜色叠加

css - 自动展开所有 PrimeNG Accordion 面板以进行打印

javascript - android:React Native 从另一个应用程序打开一个应用程序?