angular - 即使调试器显示条件为真,如果未输入块
问题描述
目标:当用户在下拉列表中选择值时进入 IF 块
问题:即使调试器显示该值为真,它也没有进入条件块。这可能是因为 html 中的任何内容吗?那里有一些小的变化,但主要是它的嵌套方式,所以我可以在页面上放置不同的东西。其他一切都保持不变
我试过的:
查看 HTML
使用 Chrome 调试器
注释掉除了带有 console.log 的单行之外的所有内容
HTML:
<form [formGroup]="_siteForm">
<div class="title-container">
<mat-card-title class="text-center" i18n="@@MoVeSeLo_H1_1">
Please Sign In
</mat-card-title>
<mat-form-field class="language-field">
<mat-select (selectionChange)="doSomething($event)" [value]="languages[i]">
<mat-option *ngFor="let language of languages" [value]="language">
{{language.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
</div>
</form>
打字稿:
//Array for dropdown
public languages = [
{ value: "en", viewValue: 'English' },
{ value: "es", viewValue: 'Spanish' }
];
//Sets default value for dropdown
if (this.localeId == "en" || this.localeId == "en-US") { this.i = 0; }
else { this.i = 1; }
//Event code when user selects an option from the dropdown
doSomething(event) {
console.log("in doSomething()");
//if value selected is spanish
if (event.value == "es") {
console.log("event.value == ES");
}
else if (event.value == "en") { console.log("event.value == EN"); }
}
调试器(这是事件对象):
值:“es”
viewValue: "西班牙语"
如果 event.value 是 es,那么为什么 if 块被跳过(并且 console.log 没有被打印)?
解决方案
您的代码不起作用,因为您正在传递$event
给函数,因此当前选择的值,即语言对象,您将获得:
event.value -- gives {value: "en", viewValue: "English"}
解决方案1:
现在您要检查对象中的选定值,然后您必须使用:
event.value.value -- gives "en"
解决方案2:
改变:
<mat-option *ngFor="let language of languages" [value]="language">
到
<mat-option *ngFor="let language of languages" [value]="language.value">
那么你当前的代码就可以正常工作了!
解决方案3:
您可以click
在 mat-option 上使用 event 并将language
对象传递给doSomething()
方法:
<mat-form-field class="language-field">
<mat-select>
<mat-option *ngFor="let language of languages" (click)="doSomething(language)" [value]="language">
{{language.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
编辑:
要绑定默认值,您可以使用控件的[ compareWith
] @Input() 属性到 mat-select:
在 TS 中添加以下函数:
defaultValue: any = { value: "es", viewValue: "Spanish" }; // your selected value object
compareValues(obj: any, targetObj: any) {
if (obj.value == targetObj.value) {
return true;
} else {
return false;
}
}
HTML修改:
- 添加
[(ngModel)]
了选定的值 - 添加了 [compareWith] 功能
<mat-form-field class="language-field">
<mat-select (selectionChange)="doSomething($event)" [compareWith]="compareValues" [(ngModel)]="defaultValue">
<mat-option *ngFor="let language of languages" [value]="language">
{{language.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
推荐阅读
- c - 无法访问地址 (C) 处的内存
- r - 有没有办法使用 tidyverse R 通过升序更改多个列名?
- python - 对于 python 数据帧中的循环替换
- bluetooth-lowenergy - 关于低功耗蓝牙连接事件的问题
- sql - Postgres 按相似日期将数据分组
- c# - 如何将 YieldAwaitable 转换为任务
- php - 此路由不支持 GET 方法。支持:POST
- python - 用漂亮的汤刮一张 WP 桌子
- optimization - 如何知道 Apache Flink 中可以链接哪些算子
- node.js - 我面临使用 Highcharts Node.js 导出服务器生成空白图像的问题