Home > other >  How to concatenate 3 inputs in angular?
How to concatenate 3 inputs in angular?

Time:09-17

i need to concatenate 3 inputs and to make one value representing a date in angular typescript.

here is it my html code:

  <td>
                      <input type="text"  placeholder="jj" class="form-control" formControlName="jj" id="jj" name="jj" [hidden]="!chkEnable.checked" style="width:50%" />
                    </td>
                    <td>
                      <input type="text" placeholder="mm" class="form-control" formControlName="mm" id="mm"  name="mm" style="width: 50%"  [hidden]="!chkEnable.checked">
                    </td>
                    <td>
                      <input type="text" placeholder="aa" class="form-control" formControlName="aa" id="aa" name="aa" style="width: 50%"  [hidden]="!chkEnable.checked">
                    </td> 

My FormGroup:

this.dateForm = this.formBuilder.group({
  jj: ['', Validators.required,Validators.max(2)],
  mm: ['', Validators.required],
  aa: ['', Validators.required]

});

thanks in advance!

CodePudding user response:

You can access your form values like that

public concatinateAll() {
   const concat = this.dateForm.controls['jj'].value   '/'  
                  this.dateForm.controls['mm'].value   '/'  
                  this.dateForm.controls['aa'].value;
   console.log(concat);
}

CodePudding user response:

Listen for form group value changes. This will fire every time any control value changes. You can perform anything you want on this.

ngOnInit() {
  this.dateSubscription = this.dateForm.valueChanges
  .pipe(map(this.formatDate))
  .subscribe(d => console.log('MM/DD/YY', d));
}

Unsubscribe on destroy

ngOnDestroy() {
  this.dateSubscription.unsubscribe();
}

Format Date method

formatDate({ aa, jj, mm }: any): string {
  return new Date(jj   '/'    mm   '/'    aa).toLocaleString();
}

To submit form

<form [formGroup]="dateForm" (ngSubmit)="onSubmit()">

In Ts,

onSubmit(): void {
    // all form data
    const fromData = this.dateForm.getRawValue();
    // generate date out of it
    const date = this.formatDate(fromData);
    // create request by adding formdata with date
    const request = { ...fromData, date };
    console.log(request);
    // API call or other operation
  }

Pass this js date as string to laravel and in laravel convert it into Date. Some thing like this...

$jsDate = '11/12/2021, 12:00:00 AM';
echo date('Y-m-d', strtotime($jsDate));

// or

$date=date_create("12/25/2021, 12:00:00 AM");
echo date_format($date,"Y/m/d H:i:s");

Demo

  • Related