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

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

Use custom select component in Reactive form using Angular 7

问题

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

自定义组件HTML-

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

自定义组件TS文件

import { Component, ChangeDetectionStrategy, ChangeDetectorRef, Input, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'app-custom-select',
  templateUrl: './custom-select.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    { 
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CustomSelectComponent),
      multi: true
    }
  ]
})
export class CustomSelectComponent implements ControlValueAccessor {
 
  selectedItems = [];
  @Input() labelStr: string;
  @Input() groupID: string;
  @Input() selectedItem: string;

  private propagateOnChange = (value: { lovId, lovValue }[]) => {};
  private propagateTouched = (value: { lovId, lovValue }[]) => {};

  titleData = [
      {
          "lovId":{"lang":"EN","lovId":"1"},
          "lovValue":"Mr"
      },
      { 
          "lovId":{"lang":"EN","lovId":"2"},
          "lovValue":"Mrs"
      },
      {
          "lovId":{"lang":"EN","lovId":"3"},
          "lovValue":"Dr"
      },
      {
          "lovId":{"lang":"EN","lovId":"5"},
          "lovValue":"Miss"
      }
  ]

  constructor(
    private cdRef: ChangeDetectorRef
  ) { 
      console.log("selected Item = "+this.selectedItem+" groupID = "+this.groupID)
  }

  writeValue(items: { lovId, lovValue }[]) {
    this.selectedItems = items;
  }

  registerOnChange(fn) {
    this.propagateOnChange = fn;
  }

  registerOnTouched(fn) {
    this.propagateTouched = fn;
  }

  change(e) {
    this.selectedItem = e.target.options[e.target.options.selectedIndex].value;
    console.log("selected Item = "+this.selectedItem)
  }
}

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

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

响应式表单TS文件

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, AbstractControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-ccn-request',
  templateUrl: './ccn-request.component.html',
  styleUrls: ['./ccn-request.component.css']
})
export class CcnRequestComponent {

   ccnForm: FormGroup;

  constructor(
    private fb: FormBuilder
  ) {
    this.ccnForm = this.fb.group({
      projectType: ['', (c: AbstractControl) => {
        return c.value && c.value.length && c.value.length > 1 ? null : { test: true }
      }]
    });

    this.ccnForm.valueChanges.subscribe(console.log);
  }

  get ccnFormControl(){ return this.ccnForm.controls; }

  onSubmit(){
      console.log("Project Name = "+this.ccnFormControl.projectType.value)
  }
}

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

英文:

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

custom component HTML-

&lt;div class=&quot;form-group custom-input-overlap&quot;&gt;
&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;
&lt;option value=&quot;&quot; selected disabled&gt;{{labelStr}}&lt;/option&gt;
&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;
&lt;/select&gt;
&lt;label for=&quot;labelStr&quot; style=&quot;left:25px;&quot;&gt;{{labelStr}}&lt;/label&gt;
&lt;/div&gt;

custom component TS file

import { Component, ChangeDetectionStrategy, ChangeDetectorRef, Input, forwardRef } from &#39;@angular/core&#39;;
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from &#39;@angular/forms&#39;;
@Component({
selector: &#39;app-custom-select&#39;,
templateUrl: &#39;./custom-select.component.html&#39;,
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [
{ 
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() =&gt; CustomSelectComponent),
multi: true
}
]
})
export class CustomSelectComponent implements ControlValueAccessor {
selectedItems = [];
@Input() labelStr:string;
@Input() groupID:string;
@Input() selectedItem:string;
private propagateOnChange = (value: {lovId, lovValue}[]) =&gt; {};
private propagateTouched = (value: {lovId, lovValue}[]) =&gt; {};
titleData = [
{
&quot;lovId&quot;:{&quot;lang&quot;:&quot;EN&quot;,&quot;lovId&quot;:&quot;1&quot;},
&quot;lovValue&quot;:&quot;Mr&quot;
},
{ 
&quot;lovId&quot;:{&quot;lang&quot;:&quot;EN&quot;,&quot;lovId&quot;:&quot;2&quot;},
&quot;lovValue&quot;:&quot;Mrs&quot;
},
{
&quot;lovId&quot;:{&quot;lang&quot;:&quot;EN&quot;,&quot;lovId&quot;:&quot;3&quot;},
&quot;lovValue&quot;:&quot;Dr&quot;
},
{
&quot;lovId&quot;:{&quot;lang&quot;:&quot;EN&quot;,&quot;lovId&quot;:&quot;5&quot;},
&quot;lovValue&quot;:&quot;Miss&quot;
}
]
constructor(
private cdRef: ChangeDetectorRef
) { 
console.log(&quot;seletced Item = &quot;+this.selectedItem+&quot; groupID = &quot;+this.groupID)
}
writeValue(items: {lovId, lovValue}[]) {
this.selectedItems = items;
}
registerOnChange(fn) {
this.propagateOnChange = fn;
}
registerOnTouched(fn) {
this.propagateTouched = fn;
}
change(e) {
this.selectedItem = e.target.options[e.target.options.selectedIndex].value;
console.log(&quot;selected Item = &quot;+this.selectedItem)
}
}

Component used in Reactive Form

&lt;form [formGroup]=&quot;ccnForm&quot; (ngSubmit)=&quot;onSubmit()&quot;&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;col-md-5 offset-md-1&quot;&gt;
&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;
&lt;/div&gt;
&lt;/div&gt;
&lt;/form&gt;

Reactive form TS file

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

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

答案1

得分: 2

在你的子组件中

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

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

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

In your child component

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

In your parent just ngOnInit just subscribe to your form

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

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:

确定