简体   繁体   中英

Set text input field display value different from actual value

Example:

const obj = {name:"abc", value:"20"};

Have to set the value as 20, but to display to the user abc.

You could use a select menu:

<select>
    <option value="20">abc</option>
    <option value="100">xyz</option>
</select>

Then the user can choose abc , but the value you get is 20 .

You don't have to post to the server the same data that the user sees. With Angular, you can keep data structures that are independent of the view and send those to the server.

For example, you could define a Product interface like this:

export interface Product {
  id: number;
  productName: string;
  productCode: string;
  category: string;
  categoryId: number;
}

The user interface could allow display/entry of a category, but the data structure could retain the value as a categoryId. You could then pass only the categoryId back to the server.

One thing is what you see and another one is what you send. Some like (it's a silly example)

<form (ngSubmit)="onSubmit()">
  <input [(ngModel)]="user">
</form>

const obj = [{name:"abc", value:"20"},{name:"def", value:"30"}];
user:any;
ngOnInit()
{
     this.user=dataToForm(20);
}
onSubmit()
{
   let data=this.formToData(this.user);
   console.log(data);
}

//we received real data and transform to display data
dataToForm(data:any)
{
   let item=obj.find(x=>x.value==data);
   return item?item.name:null
}

//we received display data and transform to real data
formToData(dataForm:any)
{
   let item=obj.find(x=>x.name==dataForm);
   return item?item.value:null

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM