Angular 在下拉列表中自动选择值
如何将值设置为下拉列表中的默认选定值?我用的是角度8。 我有下面的htmlAngular 在下拉列表中自动选择值,angular,angular8,ngx-select-dropdown,Angular,Angular8,Ngx Select Dropdown,如何将值设置为下拉列表中的默认选定值?我用的是角度8。 我有下面的html <div class="form-group"> <label class="form-control-label col-form-label-sm">Content Type</label> <select class="form-control form-control-sm" [(ngModel)]="item.contentType"
<div class="form-group">
<label class="form-control-label col-form-label-sm">Content Type</label>
<select class="form-control form-control-sm" [(ngModel)]="item.contentType" formControlName="contentType" name="contentType">
<option *ngFor="let contentType of contentTypes" [value]="contentType.name" >{{contentType.displayName}}</option>
</select>
</div>
contentTypes是一个数组,
[{“name”:“TEXT”,“displayName”:“TEXT Only”},{“name”:“AUDIO”,“displayName”:“AUDIO”},{“name”:“VIDEO”,“displayName”:“VIDEO”}]
我可以通过这个例子来实现它
模板
<div class="form-group">
<label class="form-control-label col-form-label-sm">Content Type</label>
<select class="form-control form-control-sm" formControlName="contentType"
name="contentType">
<option *ngFor="let contentType of contentTypes" [value]="contentType.name">
{{contentType.displayName}}
</option>
</select>
</div>
我希望这能对你有所帮助
默认情况下,item.contentType应该使用与contentType列表中的某些选项相关的值初始化。例如,如果使用值TEXT
初始化item.contentType
,默认情况下将预选值TEXT
的选项
或者,您可以将选项
与null
值一起放入文本选择内容
(例如)。并验证它(如果需要)。比如:
<div class="form-group">
<label class="form-control-label col-form-label-sm">Content Type</label>
<select class="form-control form-control-sm" [(ngModel)]="item.contentType"
name="contentType">
<option [value]="null">Select content</option>
<option *ngFor="let contentType of contentTypes" [value]="contentType.name">
{{contentType.displayName}}
</option>
</select>
</div>
内容类型
选择内容
{{contentType.displayName}
无论如何,请设计您将使用哪种方法来构建表单()。因为您在“选择组件”的定义中出错。如果要使用模板驱动的表单模式,请仅使用
[(ngModel)]
定义并删除formControlName=“contentType”
。在提供的链接中首先研究此问题。在初始化选择之前,是否可以为item.contentType设置默认值?将其设置为“文本”可能会预先选择文本选项,这有助于Karu将方法重写为反应式表单模式。Karu使用模板驱动的表单他同时使用这两种表单,我已经从上面的示例中删除了[ngModel]
,很好的提示,我只看到了[(ngModel)]定义。如果你有时间,如果你能为被动表单模式提供正确的解决方案,那就太好了。在您的回答中,缺少了一些内容,例如模板和ts文件中的:[formGroup]定义,当然还有contentType formControl中formGroup实例的定义
// if you will give the value to the contentType control it will be selected item
// something like this
export class ReleaseComponent implements OnInit {
ngOnInit() {
this.yourForm.get('contentType').patchValue('TEXT');
// or
this.yourForm.get('contentType').patchValue(this.contentTypes[0].name);
}
}
<div class="form-group">
<label class="form-control-label col-form-label-sm">Content Type</label>
<select class="form-control form-control-sm" [(ngModel)]="item.contentType"
name="contentType">
<option [value]="null">Select content</option>
<option *ngFor="let contentType of contentTypes" [value]="contentType.name">
{{contentType.displayName}}
</option>
</select>
</div>