簡體   English   中英

如何在 Typescript 中使用 ngModel 從 HTML 集獲取值

[英]How to get value from HTML set using ngModel in Typescript

我知道這可能是一個重復的問題。 我有一個輸入框,我在其中使用 ngModel 設置值。 現在我想獲取該值並使用打字稿存儲它。 有人可以幫助我如何做到這一點。 HTML代碼:

 <mat-label> City:
    <input class="editcustomer" [(ngModel)]="element.city" />
 </mat-label>

我是使用 getElementbyId 還是有其他方法?

你可以這樣試試

HTML

<input type="text" [ngModel]="element.city" (ngModelChange)="myFunction($event)">

TS

myFunction(event: any): any {
console.log(event); // here you are getting the value
}

但我建議您在這里實現模板驅動的表單或反應式表單,您可以找到有關該反應式模板驅動的更多信息

您正在使用反應式形式,因此這種方式更好

TS

  this.myForm = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
  });

HTML

<form [formGroup]="myForm"  (ngSubmit)="onSubmit()">
 <input type="text" formControlName="firstName">
 <input type="text" formControlName="lastName">
</form>

TS

onSubmit() {
  console.log(this.myForm); // here you will get all the values
}

當前代碼沒有問題,因為您已經將元素對象與[(ngModel)]屬性綁定,因此無需調用ngModelChange()方法。 您可以在 TS 代碼中的任何位置使用this.element來獲取具有最新值的對象。

Working Demo

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM