简体   繁体   中英

Can't set default selection property with ngmodel on Angular 9

I'm trying to create a select with a default value on Angular 9. I need two-way-binding, because the value selected must instantly be displayed in an element next to the selection. I've tried everything, from using Angular Material's implementation of option to normal selection boxes, but I can't seem to set the default selection.

I need to control the selected element with the isSelected on [selection] , but everything I've tried will display a blank selection box.

The select itself is as follows:

<select [(ngModel)]="selectedPrice">
    <option *ngFor="let value of values" [ngValue]="value.propertyName" [selected]="value.isSelected == true"> {{value.str}} </option>
</select>

The array is:

values = [{ str: 'Varejo 1', propertyName: 'varejo1', isSelected: true, },
    { str: 'Varejo 2', propertyName: 'varejo2', isSelected: false },
    { str: 'Varejo 3', propertyName: 'varejo3', isSelected: false },
    { str: 'Atacado 1', propertyName: 'atacado1',  isSelected: false },
    { str: 'Atacado 2', propertyName: 'atacado2',  isSelected: false },
  ]

The component is:

export class ProductDialogComponent implements OnInit {

  selectedPrice: number;

  values = [{ str: 'Varejo 1', propertyName: 'varejo1', isSelected: true, },
    { str: 'Varejo 2', propertyName: 'varejo2', isSelected: false },
    { str: 'Varejo 3', propertyName: 'varejo3', isSelected: false },
    { str: 'Atacado 1', propertyName: 'atacado1',  isSelected: false },
    { str: 'Atacado 2', propertyName: 'atacado2',  isSelected: false },
  ];

  constructor(
    public dialogRef: MatDialogRef<MomfortProductsTableComponent>,
    @Inject(MAT_DIALOG_DATA) public product: MomfortProduct) {
  }

  ngOnInit(): void {

  }

  onNoClick(): void {
    this.dialogRef.close();
  }

}

I currently get this:

在此处输入图像描述

How would I make it so my [selected] condition works?

You can just assign a value to selectedPrice :

In your component.ts :

this.selectedPrice = this.values.find(({ isSelected }) => isSelected ).propertyName;

or if you directly want to give it a static value:

this.selectedPrice = 'varejo1'

update

Use selectedPrice: String

and the select element can be:

<select [(ngModel)]="selectedPrice">
    <option *ngFor="let value of values" [ngValue]="value.propertyName">{{value.str}}</option>
</select>

You already have two-way binding because of [(ngModel)]="selectedPrice" whenever you want to access the value of the selected option in your component.ts just use this.selectedPrice .

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