Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

How to handle an undefined value with Angular string interpolation?

I am working on an Angular project and I have the following doubt about how correctly handle this situation where into a string interpolation defined into my template I can have undefined values. Into the HTML code of a component I have:

<td>{{file.info.meta_data.type.type}}</td>

the file.info.meta_data.type.type can be undefined and cause the following exception in the Chrome console:

ERROR TypeError: Cannot read property 'type' of undefined
    at AssetDetailsComponent_ng_template_103_Template (asset-details.component.html:285)
    at executeTemplate (core.js:7457)
    at refreshView (core.js:7326)
    at refreshEmbeddedViews (core.js:8427)
    at refreshView (core.js:7350)
    at refreshEmbeddedViews (core.js:8427)
    at refreshView (core.js:7350)
    at refreshEmbeddedViews (core.js:8427)
    at refreshView (core.js:7350)
    at refreshComponent (core.js:8473)

How can I correctly handle this situation to show an empty string in case the previous field have an undefined value? Can I handle this directly with string interpolation or have I to use an ngIf* directive on the td tag^

question from:https://stackoverflow.com/questions/65936070/how-to-handle-an-undefined-value-with-angular-string-interpolation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

simply check if it is undefined before

<td>{{file?.info?.meta_data?.type?.type}}</td>

it will show empty string if any value for file, info, meta_data, type is undefined


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...