我正在从数据库中获取产品,它们正在填充我的下拉列表。
我可以从下拉列表中选择产品,该产品包含计量单位(升、千克、盎司等)。所以基本上,当我从下拉列表中选择产品时,我想在下拉列表下方的控件中显示度量单位,如上例所示。
这是我的 html:
<div class="form-horizontal" action="">
<div class="form-group">
<label class="control-label dash-control-label col-sm-3">Title:</label>
<div class="col-sm-6">
<select class="form-control dash-form-control select2" style="width: 100%;">
<option selected disabled>Search...</option>
<option *ngFor="let ingredient of ingredients;" [value]="ingredient.id">{{ingredient.title}}</option>
</select>
</div>
<div class="col-sm-3">
<button type="button"
class="btn main-content-button mini-add-button"
data-toggle="modal"
data-target="#modal-3">
<i class="fas fa-plus"></i>
</button>
</div>
</div>
<!--Unit of measure-->
<div class="form-group">
<label class="control-label dash-control-label col-sm-3" for="user-lastname">Unit of measure:</label>
<div class="col-sm-4">
<input type="text" class="form-control dash-form-control read-only" placeholder="" value="Liter (L)" readonly>
</div>
</div>
<!--Quantity-->
<div class="form-group">
<label class="control-label dash-control-label col-sm-3" for="user-password">Quantity:</label>
<div class="col-sm-4">
<input type="text" class="form-control dash-form-control" id="user-password" placeholder="">
</div>
</div>
</div><!--End of form horizontal-->
所以基本上在我的包含计量单位的输入中,我想获得所选产品的计量单位并将其显示在那里,它只是只读字段:)
这是我从 DB 获取产品的 typescript 代码:
export class ProductIngredientNewComponent implements OnInit {
@Input() ProductId: string;
// Array that will holds all Products which represent ingredients
ingredients: Product[];
id: string;
constructor(public _productsService: ProductService) {
}
ngOnInit() {
// Here I'm getting values from DB and this values are source to dropdown
this._productsService.getAll().subscribe(ing => this.ingredients = ing);
}
}
我是否需要在选择下拉列表中的值时附加事件,以手动将值设置为 typescript 中的某些属性并以度量单位显示它,还有另一种更好、更 Angular 方式吗?
谢谢大家 干杯
最佳答案
您能否尝试使用以下代码并检查您的问题是否已解决。我遇到了同样的情况,只是我的案例中有单选按钮。想法是将您的对象保存在 Option 的值中。并为其分配一个模型,该模型将包含从选择框中选择的值并将相同的 ngmodel 绑定(bind)到您的输入。
希望它对你有用!
<div class="col-sm-6">
<select class="form-control dash-form-control select2" style="width: 100%;" [(ngModel)]="ingredient.title">
<option selected disabled>Search...</option>
<option *ngFor="let ingredient of ingredients;" [value]="ingredient">{{ingredient.title}}</option>
</select>
</div>
<input type="text" class="form-control dash-form-control read-only" placeholder="" value="Liter (L)" readonly [(ngModel)]="ingredient.title">
关于javascript - 如何根据下拉选择填充文本值类型的输入 - Angular 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51894185/