首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为隐藏的ngModel赋值

问为隐藏的ngModel赋值
EN

Stack Overflow用户
提问于 2020-04-28 13:27:20
回答 1查看 363关注 0票数 0

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

模型

代码语言:javascript
复制
export class Exp{

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

}

html

代码语言:javascript
复制
    <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

代码语言:javascript
复制
   add(){
    this.myService.add(this.exp).subscribe(
       data => {this.exp=data;}, 
       error => {console.log('error');}
     );

  }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-28 13:37:20

这里你有一个Stackblitz演示。

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

代码语言:javascript
复制
<input type="text" #first="ngModel" [(ngModel)]="exp.first" class="form-control">

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

代码语言:javascript
复制
@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();
  }
}

​

​

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61481324

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档