由于某种原因,我需要在两个输入中分配相同的值。意味着我必须在second中设置变量second的值,而不需要用户自己编写它。
模型
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');}
);
}发布于 2020-04-28 13:37:20
这里你有一个Stackblitz演示。
最初,您可以将模板引用变量设置为第一个输入,接收ngModel指令:
<input type="text" #first="ngModel" [(ngModel)]="exp.first" class="form-control">之后,您可以在类型记录上获取对该控件的引用,订阅其更改并将其复制到模型中的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();
}
}

https://stackoverflow.com/questions/61481324
复制相似问题