1

I have 1 dropdown and 1 input field. Based the selection of dropdown, input field value is set.

So i used an array of type any(Array).

In my .ts file, i wrote like this

Services: Array<any>=[
    {name: 'Consultation', price: 100}, 
    {name: 'Follow Up', price: 200}, 
    {name: '24 Hrs. Creatinine', price: 300}, 
    {name: 'Complete Blood Count - CBC', price: 400}, 
    {name: 'X-Ray', price: 500}];

 selectedservice = this.Services;

And in HTML, I wrote likes this

<div class="col-sm-9">
                <nb-select type="number" fullWidth id="service" [(ngModel)]="selectedservice"
                  [ngModelOptions]="{standalone: true}" required>
                  <nb-option *ngFor="let service of Services" [value]="service">{{service.name}} </nb-option>
                </nb-select>
</div>
<div class="col-sm-9">
                <input type="number" nbInput fullWidth id="price1" [disabled]="true"
                  value="{{selectedservice.price}}" class="form-control" />

When I run build command, ng build --aot

I was getting this error

Property 'name' does not exist on type 'any[]'.

Property 'price' does not exist on type 'any[]'.

How to resolve this

Sravan Kumar
  • 602
  • 8
  • 22

2 Answers2

1

When you want to use an object as the selected value, you should bind to [ngValue] in the <option> elements. Use [value] when the value is a string.

<div class="col-sm-9">
  <nb-select type="number" fullWidth id="service" 
      [(ngModel)]="selectedservice"
      [ngModelOptions]="{standalone: true}" required>
    <nb-option *ngFor="let service of Services" [ngValue]="service">
      {{service.name}} 
    </nb-option>
  </nb-select>
</div>

<div class="col-sm-9">
  <input *ngIf="selectedservice" type="number" nbInput fullWidth id="price1" [disabled]="true"
    value="{{selectedservice.price}}" class="form-control" />
</div>

It is also meaningless to initialise your selectedservice with the source array. You should set it to one of your options.

selectedservice = this.Services[0];

DEMO: https://stackblitz.com/edit/angular-rg8myc

Kurt Hamilton
  • 12,490
  • 1
  • 24
  • 40
0

Always try to provide a valid data type and avoid using any. It would be better to create an interface and use it in your code.

interface ServiceInterface {
  name: string;
  price: number;
}

Use this interface in your code.

Services: ServiceInterface[] = [
        {name: 'Consultation', price: 100}, 
        {name: 'Follow Up', price: 200}, 
        {name: '24 Hrs. Creatinine', price: 300}, 
        {name: 'Complete Blood Count - CBC', price: 400}, 
        {name: 'X-Ray', price: 500}];

when you are using it inside *ngFor you want to access the properties of object, it means you are assuming it as object but in declaration you have created it as array of any data type. It is not able find any type information from it and giving you an error.

Jasdeep Singh
  • 7,901
  • 1
  • 11
  • 28