【发布时间】:2019-02-15 18:47:10
【问题描述】:
我有一个名为 customers 的 JSON 文件,我在 dropdown 中显示客户,在 dropdown 中当我选择特定客户时,如何在输入字段中显示所选客户的详细信息像这样:
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();
}
}
【问题讨论】:
-
StackBlitz 对 Angular 问题非常有用,但请在问题本身中添加最相关的代码部分,因为链接可能会失效,变得无效,从而对下一个读者失去价值。
标签: angular typescript