Angular, custom input text component inside in reactive form

54 views
Skip to first unread message

Guy Biton

unread,
Jan 25, 2018, 12:52:44 PM1/25/18
to Angular and AngularJS discussion



sm-input -> my custom input text component




import { Component, Inject, Injector, Input, Optional, ViewChild, Output, EventEmitter } from '@angular/core';
import { NG_VALUE_ACCESSOR, NgModel } from '@angular/forms';
import { ValueAccessorBase } from '../base-elements/value-accessor';

@Component({
  selector: 'sm-input',

  templateUrl: './sm-input.component.html',
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: SmInputComponent,
    multi: true,
  }],
  styleUrls: ['./sm-input.component.scss'],
})
export class SmInputComponent extends ValueAccessorBase<string> {
  constructor(injector: Injector) {
    super(injector);
  }
}


sm-input html:
(i removed what not was necessary)

<div>
  <div *ngIf="label">
    <label>
       {{label}} 
    </label>
  </div>
  <div>
    <input  
      type="text" 
      pInputText
      [(ngModel)]="value"
    />
  </div>
</div>


my form: (the host of sm-input)

import { Component, OnInit } from '@angular/core';

import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';

@Component({
  selector: 'sm-input-example-in-reactive-from',
  templateUrl: './sm-input-example-in-reactive-from.component.html',
  styleUrls: ['./sm-input-example-in-reactive-from.component.scss']
})
export class SmInputExampleInReactiveFromComponent {

  public firstName: string = "Bob";
  myReactiveForm: FormGroup;
  constructor(fb: FormBuilder) {
    this.myReactiveForm = fb.group ({
      myField: [this.firstName, [Validators.required]],
    });
  }
  onSubmit(value) {
    console.log(`Submit: ${JSON.stringify(value)}`);
  }
}

html form

<p-panel header="Reactive Form">
  <form action="" [formGroup]="myReactiveForm" (ngSubmit)="onSubmit(myReactiveForm.value)">
    <div class="ui-grid-row">
      <sm-input
        label="First Name"
        formControlName="myField">
      </sm-input> 
  </div>
  <div class="ui-grid-row">
      <div class="ui-g-2 ui-g-offset-5">
          <button type="Submit" class="" pButton [disabled]="!myReactiveForm.valid">Submit</button>
        </div> 
  </div>
</form>
</p-panel>


please looking on <sm-input>.

it's working. but i don't want to use in [(ngMode)]="value" - because reactive form not need to work with ngMode.

i read this post in stackOverFlow:

its not a good idea to mix between driven form from and reactive form.

what should i do?


thank you.
Reply all
Reply to author
Forward
0 new messages