angular - 在输入字段中显示选定的对象值
问题描述
我有一个名为的 JSON 文件customers
,我在 中显示客户,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();
}
}
解决方案
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>
推荐阅读
- c++ - 这里的以下 oop 结构是什么?
- javascript - Firestore 未写入所有文档
- accelerometer - 在 SPI 中将 ICM20948 与 STM32F446RE HAL 层接口
- http - 当我在飞镖中收到异常消息时,为什么会收到“异常:”?
- python - 将 JSON 列表转换为 pandas 数据框
- node.js - 如何从nodejs中的json对象获取值
- javascript - 如何在 ReactJS 中获取内部 API 数据?
- json - 使用 Goodreads API 时出现 json.decoder.JSONDecodeError
- python - 制作实时处理数据的动画时间序列图
- c++ - 为什么带有指针子对象的文字类类型的 constexpr 表达式不能是非类型模板参数