angular - Typescript变量中问号(?)的用途是什么?

标签 angular typescript

我看到了在插值QuestionMark里面进行内插的情况?与变量名一起使用。
示例:current?.sample.innerSample
我不确定它是干什么用的。
任何帮助深表感谢。

谢谢

最佳答案

?.是安全的导航操作符。它可以防止对象路径出现undefinednull reference错误。例如:

如果您在{{ data.somepropertyname }}文件中写入template而未在data文件中定义typescript成员变量,则会引发如下错误

Cannot get somepropertyname of undefined



但是,如果您这样写{{data?.somepropertyname}},则不会抛出错误

检查示例Stackblitz

执行注释和取消注释行号8 & 9,您将在控制台中看到输出

关于angular - Typescript变量中问号(?)的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52251917/

相关文章:

typescript - 捆绑和使用 webpack 构建的 typescript 库的正确方法?

reactjs - styled-components:使用额外的样式扩展现有组件

angular - 类型 'element' .ts 上不存在属性 'Directive'

dart - Angular2 Dart构建使 “The selector ”演示应用程序“与任何元素都不匹配”错误

javascript - 使用可管道化的 RxJs 操作符实现复杂的文件上传场景?

unit-testing - Angular 2 - TestBed.configureTestingModule - 供应商 :[] throws Use of reserved word 'import' error

typescript - 在一个 Electron 应用程序中,仅在 main.ts 中导入 libp2p 会导致 "self is not defined"

javascript - Angular 7 中的 Controller 在哪里,因为它遵循 mvc 架构

html - Angular - 在另一个组件的输入文本框中设置值

html - Angular 4 全图背景