我必须首先将component属性设置为null,因为在页面加载时我希望输入为空。我需要检查字符串是否为空,但是当它为null时我不能这样做,实际上,从用户角度来看,一切仍然可行,但是会引发错误,因此我想我不应该这样做。那么如何检查带有可为空变量的空字符串?
export class ExpensesLogComponent implements OnInit {
inputHelperTextVisible: boolean = false;
expenses: number = null;
检查是否为空:
onKey(event: any) {
if (event.key === 'Enter') {
console.log('enter pressed!');
}
// error is this.expenses = null
if (this.expenses.toString() === '') {
this.inputHelperTextVisible = false;
} else {
this.inputHelperTextVisible = true;
}
}
答案 0 :(得分:0)
您是否尝试过删除toString?
SELECT (SUM(DATEPART(HOUR, InTime) * 60) + SUM(DATEPART(MINUTE, InTime))) / (SELECT COUNT(InTime) FROM #Temp WHERE DATEPART(HOUR, InTime) <> 0) / 60 AS [InTime avg hours]
, (SUM(DATEPART(HOUR, InTime) * 60) + SUM(DATEPART(MINUTE, InTime))) / (SELECT COUNT(InTime) FROM #Temp WHERE DATEPART(HOUR, InTime) <> 0) % 60 AS [InTime avg minutes]
, (SUM(DATEPART(HOUR, OutTime) * 60) + SUM(DATEPART(MINUTE, OutTime))) / (SELECT COUNT(OutTime) FROM #Temp WHERE DATEPART(HOUR, OutTime) <> 0) / 60 AS [OutTime avg hours]
, (SUM(DATEPART(HOUR, OutTime) * 60) + SUM(DATEPART(MINUTE, OutTime))) / (SELECT COUNT(OutTime) FROM #Temp WHERE DATEPART(HOUR, OutTime) <> 0) % 60 AS [OutTime avg minutes]
FROM #Temp
如果使用==而不是===,除了检查费用是否为null之外,还将检查费用是否未定义。
答案 1 :(得分:0)
您不必设置为空
export class ExpensesLogComponent implements OnInit {
inputHelperTextVisible = false;
expenses: number;
并检查是否为空
if (!this.expenses || this.expenses.toString() == '') { }
答案 2 :(得分:0)
您有几种选择可以避免出错。 但是我建议使用嵌套循环之一以避免打字稿出现任何问题。
// it will work
if(this.expenses != null) {
if (this.expenses.toString() === '') {
this.inputHelperTextVisible = false;
} else {
this.inputHelperTextVisible = true;
}
} else{
this.inputHelperTextVisible = false;
}