angular - 传递数据以形成控制角度
问题描述
我有一个带有 2 个控件的表单组
this.firstFormGroup = this._formBuilder.group({
name: [''],
description: [''],
});
我使用 *ngFor 遍历具有这两个属性(名称和描述)的对象数组(我的数据库)
<form [formGroup]="firstFormGroup">
<ng-template matStepLabel>Choose a bike</ng-template>
<mat-form-field appearance="fill">
<mat-label>Choose a bike</mat-label>
<mat-select formControlName="name" required>
<mat-option *ngFor="let bike of bikes" [value]="bike.name">
{{ bike.name }}</mat-option
>
</mat-select>
</mat-form-field>
</form>
D B:
export const BIKES: Bike[] = [
{
id: 1,
imgUrl:
'https://cyclingmagazine.ca/wp-content/uploads/2018/10/Krypton_A18_2016_red_ultegra_16_1.jpg',
price: 28000,
discount: 71,
main: true,
shop: 'Canada Bike',
name: 'Argon 18',
description:
'Founded by retired cyclist Gervais Rioux in Montreal in 1989, Argon 18 has grown to distribute bikes aross the world and sponsors a number of professional cycling teams and triathletes. In 2019, Argo 18 sponsores Hugo Houle’s U CI WorldTour team Astana',
shipping: 'Free shipping',
discountUntil: '2021-06-02T10:00:00',
new: true,
color: ['Blue', 'Grey', 'Orange', 'Black'],
size: ['S', 'L', 'XL', 'XXL'],
review: [
{
author: 'Michel Delap',
text: 'Good one, but I have some problem with wheels',
rating: 4,
},
],
},
我想将所选自行车的描述属性传递给描述表单控件。
我试图将 description 属性作为具有 formControlName="description" 的隐藏输入的值,但它不起作用
解决方案
Add change event in your html
<mat-select formControlName="name" required (change)="assignDescription($event)" >
<mat-option *ngFor="let bike of bikes" [value]="bike.name">
{{ bike.name }}</mat-option>
</mat-select>
in your .ts
assignDescription(event: any) {
const bikeName = this.firstFormGroup.name.value;
if (this.firstFormGroup.name.value) {
const selectedBike = this.bikes.filter((bike) => bike.name === bikeName);
this.firstFormGroup.description.value = selectedBike.description;
}
}
推荐阅读
- javascript - 将 Express 中间件添加到 NextJS typrescript 后网站未呈现
- node.js - 第一次部署,我不知道为什么它不起作用
- python - FlaskForm 多重验证和条件验证
- javascript - 从行数据复制到 JavaScript 中的剪贴板
- firebase - Firebase 用户上次登录日期返回今天的日期
- neo4j - Neo4j/Cypher 导入 CSV 文件
- kubernetes - k8s Pod 1 获取错误 pod 2 的 IP 地址
- line - 如何根据他们在android中调整视图
- flutter - 获取初始路由颤动的查询参数
- sml - SML:为什么返回类型是单位?