在使用Angular 7的响应式表单中使用自定义选择组件

huangapple go评论101阅读模式
英文:

Use custom select component in Reactive form using Angular 7

问题

我在单击“Submit”按钮时没有得到自定义组件的值。以下是我迄今为止尝试过的内容。

自定义组件HTML-

  1. <div class="form-group custom-input-overlap">
  2. <select class="form-control custom-select" (change)="change($event)" [ngClass]="{'filledTxt': selectedItem.length > 0}">
  3. <option value="" selected disabled>{{labelStr}}</option>
  4. <option *ngFor="let item of titleData" [value]="item.lovId.lovId" [selected]="item.lovId.lovId == selectedItem">{{ item.lovValue }}</option>
  5. </select>
  6. <label for="labelStr" style="left:25px;">{{labelStr}}</label>
  7. </div>

自定义组件TS文件

  1. import { Component, ChangeDetectionStrategy, ChangeDetectorRef, Input, forwardRef } from '@angular/core';
  2. import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
  3. @Component({
  4. selector: 'app-custom-select',
  5. templateUrl: './custom-select.component.html',
  6. changeDetection: ChangeDetectionStrategy.OnPush,
  7. providers: [
  8. {
  9. provide: NG_VALUE_ACCESSOR,
  10. useExisting: forwardRef(() => CustomSelectComponent),
  11. multi: true
  12. }
  13. ]
  14. })
  15. export class CustomSelectComponent implements ControlValueAccessor {
  16. selectedItems = [];
  17. @Input() labelStr: string;
  18. @Input() groupID: string;
  19. @Input() selectedItem: string;
  20. private propagateOnChange = (value: { lovId, lovValue }[]) => {};
  21. private propagateTouched = (value: { lovId, lovValue }[]) => {};
  22. titleData = [
  23. {
  24. "lovId":{"lang":"EN","lovId":"1"},
  25. "lovValue":"Mr"
  26. },
  27. {
  28. "lovId":{"lang":"EN","lovId":"2"},
  29. "lovValue":"Mrs"
  30. },
  31. {
  32. "lovId":{"lang":"EN","lovId":"3"},
  33. "lovValue":"Dr"
  34. },
  35. {
  36. "lovId":{"lang":"EN","lovId":"5"},
  37. "lovValue":"Miss"
  38. }
  39. ]
  40. constructor(
  41. private cdRef: ChangeDetectorRef
  42. ) {
  43. console.log("selected Item = "+this.selectedItem+" groupID = "+this.groupID)
  44. }
  45. writeValue(items: { lovId, lovValue }[]) {
  46. this.selectedItems = items;
  47. }
  48. registerOnChange(fn) {
  49. this.propagateOnChange = fn;
  50. }
  51. registerOnTouched(fn) {
  52. this.propagateTouched = fn;
  53. }
  54. change(e) {
  55. this.selectedItem = e.target.options[e.target.options.selectedIndex].value;
  56. console.log("selected Item = "+this.selectedItem)
  57. }
  58. }

在响应式表单中使用的组件

  1. <form [formGroup]="ccnForm" (ngSubmit)="onSubmit()">
  2. <div class="row">
  3. <div class="col-md-5 offset-md-1">
  4. <app-custom-select formControlName="projectType" labelStr="Project type" groupID="CM_GENDER" selectedItem="3"></app-custom-select>
  5. </div>
  6. </div>
  7. </form>

响应式表单TS文件

  1. import { Component, OnInit } from '@angular/core';
  2. import { FormGroup, FormBuilder, AbstractControl, Validators } from '@angular/forms';
  3. @Component({
  4. selector: 'app-ccn-request',
  5. templateUrl: './ccn-request.component.html',
  6. styleUrls: ['./ccn-request.component.css']
  7. })
  8. export class CcnRequestComponent {
  9. ccnForm: FormGroup;
  10. constructor(
  11. private fb: FormBuilder
  12. ) {
  13. this.ccnForm = this.fb.group({
  14. projectType: ['', (c: AbstractControl) => {
  15. return c.value && c.value.length && c.value.length > 1 ? null : { test: true }
  16. }]
  17. });
  18. this.ccnForm.valueChanges.subscribe(console.log);
  19. }
  20. get ccnFormControl(){ return this.ccnForm.controls; }
  21. onSubmit(){
  22. console.log("Project Name = "+this.ccnFormControl.projectType.value)
  23. }
  24. }

如何在Angular响应式表单的“Submit”按钮上获取自定义组件值?

英文:

I am not getting value on click of Submit button. Below is what I tried so far.

custom component HTML-

  1. &lt;div class=&quot;form-group custom-input-overlap&quot;&gt;
  2. &lt;select class=&quot;form-control custom-select&quot; (change)=&quot;change($event)&quot; [ngClass]=&quot;{&#39;filledTxt&#39;: selectedItem.length &gt; 0}&quot;&gt;
  3. &lt;option value=&quot;&quot; selected disabled&gt;{{labelStr}}&lt;/option&gt;
  4. &lt;option *ngFor=&quot;let item of titleData&quot; [value]=&quot;item.lovId.lovId&quot; [selected]=&quot;item.lovId.lovId == selectedItem&quot; &gt;{{ item.lovValue }}&lt;/option&gt;
  5. &lt;/select&gt;
  6. &lt;label for=&quot;labelStr&quot; style=&quot;left:25px;&quot;&gt;{{labelStr}}&lt;/label&gt;
  7. &lt;/div&gt;

custom component TS file

  1. import { Component, ChangeDetectionStrategy, ChangeDetectorRef, Input, forwardRef } from &#39;@angular/core&#39;;
  2. import { ControlValueAccessor, NG_VALUE_ACCESSOR } from &#39;@angular/forms&#39;;
  3. @Component({
  4. selector: &#39;app-custom-select&#39;,
  5. templateUrl: &#39;./custom-select.component.html&#39;,
  6. changeDetection: ChangeDetectionStrategy.OnPush,
  7. providers: [
  8. {
  9. provide: NG_VALUE_ACCESSOR,
  10. useExisting: forwardRef(() =&gt; CustomSelectComponent),
  11. multi: true
  12. }
  13. ]
  14. })
  15. export class CustomSelectComponent implements ControlValueAccessor {
  16. selectedItems = [];
  17. @Input() labelStr:string;
  18. @Input() groupID:string;
  19. @Input() selectedItem:string;
  20. private propagateOnChange = (value: {lovId, lovValue}[]) =&gt; {};
  21. private propagateTouched = (value: {lovId, lovValue}[]) =&gt; {};
  22. titleData = [
  23. {
  24. &quot;lovId&quot;:{&quot;lang&quot;:&quot;EN&quot;,&quot;lovId&quot;:&quot;1&quot;},
  25. &quot;lovValue&quot;:&quot;Mr&quot;
  26. },
  27. {
  28. &quot;lovId&quot;:{&quot;lang&quot;:&quot;EN&quot;,&quot;lovId&quot;:&quot;2&quot;},
  29. &quot;lovValue&quot;:&quot;Mrs&quot;
  30. },
  31. {
  32. &quot;lovId&quot;:{&quot;lang&quot;:&quot;EN&quot;,&quot;lovId&quot;:&quot;3&quot;},
  33. &quot;lovValue&quot;:&quot;Dr&quot;
  34. },
  35. {
  36. &quot;lovId&quot;:{&quot;lang&quot;:&quot;EN&quot;,&quot;lovId&quot;:&quot;5&quot;},
  37. &quot;lovValue&quot;:&quot;Miss&quot;
  38. }
  39. ]
  40. constructor(
  41. private cdRef: ChangeDetectorRef
  42. ) {
  43. console.log(&quot;seletced Item = &quot;+this.selectedItem+&quot; groupID = &quot;+this.groupID)
  44. }
  45. writeValue(items: {lovId, lovValue}[]) {
  46. this.selectedItems = items;
  47. }
  48. registerOnChange(fn) {
  49. this.propagateOnChange = fn;
  50. }
  51. registerOnTouched(fn) {
  52. this.propagateTouched = fn;
  53. }
  54. change(e) {
  55. this.selectedItem = e.target.options[e.target.options.selectedIndex].value;
  56. console.log(&quot;selected Item = &quot;+this.selectedItem)
  57. }
  58. }

Component used in Reactive Form

  1. &lt;form [formGroup]=&quot;ccnForm&quot; (ngSubmit)=&quot;onSubmit()&quot;&gt;
  2. &lt;div class=&quot;row&quot;&gt;
  3. &lt;div class=&quot;col-md-5 offset-md-1&quot;&gt;
  4. &lt;app-custom-select formControlName=&quot;projectType&quot; labelStr=&quot;Project type&quot; groupID=&quot;CM_GENDER&quot; selectedItem=&quot;3&quot; &gt;&lt;/app-custom-select&gt;
  5. &lt;/div&gt;
  6. &lt;/div&gt;
  7. &lt;/form&gt;

Reactive form TS file

  1. import { Component, OnInit } from &#39;@angular/core&#39;; import { FormGroup, FormBuilder, AbstractControl, Validators } from &#39;@angular/forms&#39;;
  2. @Component({ selector: &#39;app-ccn-request&#39;, templateUrl: &#39;./ccn-request.component.html&#39;, styleUrls: [&#39;./ccn-request.component.css&#39;] }) export class CcnRequestComponent {
  3. ccnForm: FormGroup;
  4. constructor(
  5. private fb: FormBuilder ) {
  6. this.ccnForm = this.fb.group({
  7. projectType: [&#39;&#39;, (c: AbstractControl) =&gt; {
  8. return c.value &amp;&amp; c.value.length &amp;&amp; c.value.length &gt; 1 ? null : { test: true }
  9. }]
  10. });
  11. this.ccnForm.valueChanges.subscribe(console.log); }
  12. get ccnFormControl(){ return this.ccnForm.controls; }
  13. onSubmit(){
  14. console.log(&quot;Project Name = &quot;+this.ccnFormControl.projectType.value) }
  15. }

How can I get the value of custom component value on Submit button in Angular Reactive Form?

答案1

得分: 2

在你的子组件中

  1. change(e) {
  2. this.selectedItem = e.target.options[e.target.options.selectedIndex].value;
  3. console.log("selected Item = " + this.selectedItem)
  4. this.propagateOnChange({selectedItem: this.selectedItem});
  5. }

在你的父组件中,只需在 ngOnInit 中订阅你的表单

  1. this.ccnForm.controls.projectType.valueChanges
  2. .subscribe(selectedItem => {
  3. // 在这里处理你的选定项目
  4. this.selectedItem = selectedItem;
  5. });
英文:

In your child component

  1. change(e) {
  2. this.selectedItem = e.target.options[e.target.options.selectedIndex].value;
  3. console.log(&quot;selected Item = &quot;+this.selectedItem)
  4. this.propagateOnChange({selectedItem: this.selectedItem});
  5. }

In your parent just ngOnInit just subscribe to your form

  1. this.ccnForm.controls.projectType.valueChanges
  2. .subscribe(selectedItem =&gt; {
  3. // Do something here with your selected item
  4. this.selectedItem = selectedItem;
  5. });

huangapple
  • 本文由 发表于 2020年1月3日 20:00:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/59578279.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定