为隐藏的 ngModel 赋值

assign value to hidden ngModel

出于某种原因,我需要在两个输入中分配相同的值。意味着我必须在 second 中设置变量 first 的值,而不需要用户自己编写

型号

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');}
     );

  }

这里有一个Stackblitz demo

最初,您可以将模板引用变量设置为第一个输入,接收 ngModel 指令:

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

之后,您可以在 typescript 上获取对该控件的引用,订阅其更改并将其复制到模型中的 second

@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();
  }
}