Problem with mat-select when submitting form in angular

筅森魡賤 提交于 2019-12-24 15:02:02

问题


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.

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.

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


回答1:


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 :)

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 } ]
})

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

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

Your forked StackBlitz



来源:https://stackoverflow.com/questions/58023895/problem-with-mat-select-when-submitting-form-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!