[Angular2] select (drop-down menu) How to set the default options, how to display the selected value and value is key

select (drop-down menu) How to set the default options, how to display the selected value and value is key


Foreword

Official website html little mention about some of the practices of the drop-down menu of their own because of some special requirements, so writing an article about the record.

example

How to give a default value, and if not selected, then the state is not verified by it? Please refer to the following example

import { Component } from '@angular/core';
import { NgForm } from "@angular/forms/src/directives";


@Component({
  selector: 'app-root',
  template: `
    
  
  
`, }) export class AppComponent { modelValue = ''; //绑定ngModel的部分 list = [ //下拉菜单的值 { key: 1, value: 'anson' }, { key: 2, value: 'jacky' }, { key: 3, value: 'andy' }, ] constructor() { } submit(form1: NgForm) { console.log(form1.valid, form1.value); } }

There is another situation is in fact, often are displayed on the screen to the user sees as text, but to send back real time db is a key way to go back, whether it is new or do another search , that this is again how to do it

  template: `
    
  
  
`

Suppose I want to set the default value if it anson

import { Component } from '@angular/core';
import { NgForm } from "@angular/forms/src/directives";


@Component({
  selector: 'app-root',
  template: `
    
  
  
`, }) export class AppComponent { modelValue: number; //绑定ngModel的部分 list = [ //下拉菜单的值 { key: 1, value: 'anson' }, { key: 2, value: 'jacky' }, { key: 3, value: 'andy' }, ] title: string; constructor() { const selectedItem = this.list.filter(x => x.key === 1)[0]; //自己用filter的方式把值选给绑定的变量 this.modelValue = selectedItem.key; //因为目前绑定的值是key,所以必须为key值哦 } submit(form1: NgForm) { console.log(form1.valid, form1.value); } }

in conclusion

Simply record what practices on the drop-down menu.

Original: Large column  [angular2] select (drop-down menu) How to set the default options, how to display the selected value and value is key


Guess you like

Origin www.cnblogs.com/chinatrump/p/11505183.html
Recommended