首页 > 解决方案 > 在输入字段中显示选定的对象值

问题描述

我有一个名为的 JSON 文件customers,我在 中显示客户,dropdowndropdown我选择特定客户时,如何在输入字段中显示所选客户的详细信息,如下所示:

在此处输入图像描述

HTML

<mat-form-field>
  <mat-select placeholder="Select Customer">
    <mat-option *ngFor="let customer of customers" [value]="customer.id">
      {{customer.name}}
    </mat-option>
  </mat-select>
</mat-form-field>

<mat-form-field>
    <input matInput placeholder="Name" matInput >
</mat-form-field>
<mat-form-field>
   <input matInput  placeholder="Email" matInput >
</mat-form-field>

TS

import { Component, OnInit } from '@angular/core';
import { ContactService } from '../contacts.service';
import { ICustomer } from '../models';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {
  public customers: ICustomer;
  constructor(private myService: ContactService) { }

  public async ngOnInit(): Promise<void> {
    this.customers = await this.myService.getCustomers('');
  }


}

服务文件(contacts.service.ts)

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ICustomer } from './models';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class ContactService {
  private baseUrl: string = '../../assets/customers.json';

  constructor(private http: HttpClient) { }


  public getCustomers(id: string): Promise<ICustomer> {
    const apiUrl: string = '../../assets/customers.json';

    return this.http.get<ICustomer>(apiUrl + id).toPromise();
  }

}

演示

标签: angulartypescript

解决方案


You need to update the template to this


<div class="main-div">
<mat-form-field>
  <mat-select placeholder="Select Customer" [(ngModel)]="customer">
    <mat-option *ngFor="let customer of customers" [value]="customer">
      {{customer.name}}
    </mat-option>
  </mat-select>
</mat-form-field>

<mat-form-field>
    <input matInput placeholder="Name" matInput [value]="customer?.name" >
</mat-form-field>

<mat-form-field>
   <input matInput  placeholder="Email" matInput [value]="customer?.email" >
</mat-form-field>

</div> 

推荐阅读