以角度提交表单时 mat-select 的问题 [英] Problem with mat-select when submitting form in angular

查看:21
本文介绍了以角度提交表单时 mat-select 的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Angular7 与 Angular Material 一起使用,我有一个表单,其中包含一个包含 mat-select 的组件.表单中的选择从我的组件中起作用,但在我的组件中不起作用.

I use Angular7 with Angular Material, I have a form which contain a component which contain a mat-select. The select in the form out of my component work but not the one into my component.

可在此 stackblitz 上查看:https://stackblitz.com/edit/angular-hqkcgq

Viewable on this stackblitz : https://stackblitz.com/edit/angular-hqkcgq

实际结果是提交表单不发送选择的值,但它必须发送.提交表单时,您可以在控制台中看到.

The actual result is that submiting form don't send the value of the select, but it have to. You can see in console when submiting the form.

stackblitz 被编辑,现在可以按我的意愿工作

edit: the stackblitz is edited and now work as I want

推荐答案

为了将来,请将所有相关代码添加到问题本身.StackBlitz 很棒,但它应该只是问题的补充:)

For future, please add all relevant code to the question itself. A StackBlitz is great, but it should just be an addition to the question :)

但是对于您的代码,您需要在您的子组件中提供 ControlContainer.所以添加到您的代码中:

But to your code, in your child component you need to provide ControlContainer. So add to your code:

import { ControlContainer, NgForm } from '@angular/forms';

@Component({
  selector: 'my-comp',
  templateUrl: './my-comp.component.html',
  viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]
})

请参考很棒的 Alexey Zuev 的文章:嵌套模板驱动的表单

Please refer to the article by the awesome Alexey Zuev: Nested Template driven Forms

作为旁注,在您提供 [ngModel]="''" 的所有地方,您只需使用 ngModel 来注册表单控件.

As a sidenote, in all places you are providing [ngModel]="''", you can just use ngModel to register the form control.

你分叉的 StackBlitz

这篇关于以角度提交表单时 mat-select 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆