select 选项的自定义属性并从 Angular 5 中的 AbstractControl 访问它?
Custom attribute for select option and accessing it from AbstractControl in Angular 5?
我想为 select 元素中的每个选项元素创建自定义属性,但我在创建可以通过 AbstractControl 和 event.target 访问的属性时遇到了问题。这是我拥有的:
我尝试创建一个名为 code 的自定义属性,然后尝试使用 id。
<select id="country" formControlName="country" class="form-control" (change)="getStates($event.target.value, $event.target.id)">
<option id = "{{cntry.code}}" *ngFor="let cntry of countries" [value]="cntry.id" [attr.code] = "cntry.code">{{cntry.name}}</option>
</select>
在代码的其他地方,我有:
editForm.controls['country'].id
我之前试过
editForm.controls['country'].code
但这也没有用。我已经为选项元素设置了值,所以我不能使用它。该属性必须可通过 AbstractControl 和 event.target.
访问
在组件的 TypeScript 中添加 属性 个国家/地区
country: Country; // Whatever type your countries are
然后使用 ngModel 绑定到国家并使用 ngValue 作为选项并绑定到国家对象
<select id="country" formControlName="country" class="form-control" [(ngModel)]="country" (change)="getStates()">
<option *ngFor="let cntry of countries" [ngValue]="cntry">{{cntry.name}}</option>
</select>
然后在您的 getStates 方法中,您可以在具有 this.country
的组件上使用 属性
如果您在 select 上收到 no ngModel 属性 错误,那么您需要将 Angular 表单模块添加到您的模块中。
我想为 select 元素中的每个选项元素创建自定义属性,但我在创建可以通过 AbstractControl 和 event.target 访问的属性时遇到了问题。这是我拥有的:
我尝试创建一个名为 code 的自定义属性,然后尝试使用 id。
<select id="country" formControlName="country" class="form-control" (change)="getStates($event.target.value, $event.target.id)">
<option id = "{{cntry.code}}" *ngFor="let cntry of countries" [value]="cntry.id" [attr.code] = "cntry.code">{{cntry.name}}</option>
</select>
在代码的其他地方,我有:
editForm.controls['country'].id
我之前试过
editForm.controls['country'].code
但这也没有用。我已经为选项元素设置了值,所以我不能使用它。该属性必须可通过 AbstractControl 和 event.target.
访问在组件的 TypeScript 中添加 属性 个国家/地区
country: Country; // Whatever type your countries are
然后使用 ngModel 绑定到国家并使用 ngValue 作为选项并绑定到国家对象
<select id="country" formControlName="country" class="form-control" [(ngModel)]="country" (change)="getStates()">
<option *ngFor="let cntry of countries" [ngValue]="cntry">{{cntry.name}}</option>
</select>
然后在您的 getStates 方法中,您可以在具有 this.country
的组件上使用 属性如果您在 select 上收到 no ngModel 属性 错误,那么您需要将 Angular 表单模块添加到您的模块中。