角度 8 选择选项编号和字母



>我对所选选项有问题

当name_step = "ABCD" 被选中但

未选择 name_step = "1" 时。

为什么会发生这种情况,即使我将两者都设置为字符串

这是我的代码:

<option *ngFor="let step of listStep | keyvalue" value={{step.value.id}}  selected="{{step.value.name === name_step ? 'selected' : '' }}">
{{ step.value.name | titlecase }}</option>

我有 3 个选择

option 1 [id = 1, name = "1"],
option 2 [id = 2, name = "2"],
option 3 [id = 3, name = "ABCD"]

这段代码name_step:

this.name_step = params['params']['name_step'];

现场演示

我不确定我是否正确回答了您的问题,但您可能会问这样的事情吗

<mat-form-field>
<mat-label>Cars</mat-label>
<select matNativeControl required>
<option *ngFor="let step of listStep " value={{step.id}}  selected="{{step.name == name_step ? 'selected' : '' }}">
{{ step.name | titlecase }}</option>
</select>
</mat-form-field>

Ts文件代码

name_step='ABCD';
listStep: any[] = [
{ id: 1, name: "1" },
{ id: 2, name: "2" },
{ id: 3, name: "ABCD" }
];

如果要在页面加载时保持选中"1",可以执行以下操作:

元件:

listStep = [
{id : 1, name : "1"},
{id : 2, name : "2"},
{id : 3, name : "ABCD"}
]
selectedStep = this.listStep.find(x=>x.id == 1); //Keep 1 selected.
onChange(){
console.log(this.selectedStep);
}

.HTML:

<select class="form-control" [(ngModel)]="selectedStep" (change)="onChange()">
<option *ngFor="let step of listStep" [ngValue]="step">{{step.name}}</option>
</select>

堆栈闪电战演示

最新更新