[英]Unable to bind the dynamic data into Angular Material select form
I am unable to display the data dynamically with Angular Material select form using Angular8.我无法使用 Angular8 使用 Angular Material 选择表单动态显示数据。 My code is below.
我的代码如下。
product.componet.html: product.componet.html:
<form [formGroup]="productForm" (submit)="saveProduct($event)" novalidate>
<mat-form-field appearance="outline" class="col-lg-4 col-md-6 col-sm-12">
<mat-label>Product Name</mat-label>
<input matInput placeholder="Product Name" aria-label="Product Name" formControlName="Name" maxlength="70" required>
</mat-form-field>
<mat-form-field appearance="outline" class="col-lg-4 col-md-6 col-sm-12">
<mat-label>Gender</mat-label>
<mat-select
placeholder="Select Gender"
aria-label="Select Gender"
(selectionChange)="onGenderSelectionChanged($event)"
>
<mat-option *ngFor="let s of genders" [value]="s.Code">
<span *ngIf="!s.Code">
</span>
<span *ngIf="s.Code">
{{s.Name}}
</span>
</mat-option>
</mat-select>
</mat-form-field>
</form>
Product.componet.ts: Product.component.ts:
genders: any = [
'',
{
Code: "M",
Name: "Male"
},
{
Code: "F",
Name: "Female"
},
{
Code: "U",
Name: "Unisex"
}
];
this.productForm.setValue({
Name : String = 'Test product',
Gender: String = 'M(Male)'
})
I am able to display the product name but unable to display that drop down value which is binding dynamically.我能够显示产品名称,但无法显示动态绑定的下拉值。 I need to display the drop down value dynamically using Angular 8.
我需要使用 Angular 8 动态显示下拉值。
There are few things which is wrong in the posted code:发布的代码中有几件事是错误的:
formControlName
for the gender control for the <mat-select>
control:formControlName
用于<mat-select>
控件的性别控制: Ex:前任:
Here
\/\/\/\/\/\/
<mat-select formControlName="Gender" placeholder="Select Gender" aria-label="Select Gender" (selectionChange)="onGenderSelectionChanged($event)">
<mat-option *ngFor="let s of genders" [value]="s.Code">
<span *ngIf="!s.Code"></span>
<span *ngIf="s.Code"> {{s.Name}}</span>
</mat-option>
</mat-select>
this.productForm.setValue({
Name : 'Test product',
Gender: 'M'
});
Not M(Male)
which is totally diff.不是完全不同的
M(Male)
。 from M
, which you are using to bind the value of matselect.来自
M
,您使用它来绑定 matselect 的值。
Instead of checking try using to set the value as ""而不是检查尝试使用将值设置为“”
<span>
{{s.Name}}
</span>
And your array as而你的阵列作为
genders: any = [
{
Code: "",
Name: ""
},
{
Code: "M",
Name: "Male"
},
{
Code: "F",
Name: "Female"
},
{
Code: "U",
Name: "Unisex"
}
];
Setting the mat select value设置垫子选择值
<mat-select placeholder="Select Gender" aria-label="Select Gender" (selectionChange)="onGenderSelectionChanged($event)" formControlName="Gender">
<mat-option *ngFor="let s of genders" [value]="s.Code">
<span *ngIf="!s.Code"></span>
<span *ngIf="s.Code">
{{s.Name}}
</span>
</mat-option>
</mat-select>
Add the formControlName to the mat select tag将 formControlName 添加到 mat select 标签
formControlName="Gender"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.