eze
eze

Reputation: 55

assign value to hidden ngModel

for some reason I need to assign the same value in two input. means I have to set the value of the variable first in second without the need for the user to write it himself

model

export class Exp{

    id: number;
    first: any;
    second: any;

}

html

    <label>enter value of first :</label>
    <input type="text" [(ngModel)]="exp.first" class="form-control">

     <input type="hidden" [(ngModel)]="exp.second" class="form-control">

           <button (click)="add()">add</button>

ts

   add(){
    this.myService.add(this.exp).subscribe(
       data => {this.exp=data;}, 
       error => {console.log('error');}
     );

  }

Upvotes: 0

Views: 735

Answers (1)

julianobrasil
julianobrasil

Reputation: 9377

Here you have a Stackblitz demo.

Initially, you can set a template reference variable to the first input, receiving the ngModel directive:

<input type="text" #first="ngModel" [(ngModel)]="exp.first" class="form-control">

After that, you can grab a reference to that control on typescript, subscribe to its changes and copy it to second in model:

@ViewChild('first') _ngModelFirst: NgModel;

// Best practice: let's unsubscribe from all observables
// when this component is destroyed
private _destroy$ = new Subject<void>();

exp: Exp = {
  id: 1,
  first: '',
  second: ''
};

ngAfterViewInit() {
  this._ngModelFirst.valueChanges
    // Best practice: this pipe is just to finish the subscription
    // when this._destroy$ emits
    .pipe(takeUntil(this._destroy$))
    .subscribe((value: string | null) => {
      this.exp.second = value;
    });
}

ngOnDestroy() {
  if (this._destroy$ && !this._destroy$) {
    this._destroy$.next();
    this._destroy$.complete();
  }
}

enter image description here

Upvotes: 1

Related Questions