ng-배열이 비어 있는지 확인합니다.
사용 중인 API는 배열에 항목이 없는 경우 이 값을 반환합니다.
items: []
어레이에 아이템이 있는 경우 다음과 같은 것이 반환됩니다.
items: [
{
name: 'Bla'
}
]
템플릿에서 데이터가 있는지 여부에 따라 요소를 표시하거나 숨기려면 ng-if를 사용해야 한다고 생각합니다.
<p ng-if="post.capabilities.items"><strong>Topics</strong>: <span ng-repeat="topic in post.capabilities.items">{{topic.name}}</p>
하지만 Angular에서 일하는 것은 처음이고, 제가 하려는 일을 더 잘 할 수 있는 방법이 있을지도 모르기 때문에 완전히 잘못될 수도 있습니다.
post.capabilities.items
빈 배열이기 때문에 계속 정의됩니다.post.capabilities.items.length
잘 될 거야 왜냐하면0
거짓이야.
를 확인합니다.length
다음보다 큰 배열의 속성0
:
<p ng-if="post.capabilities.items.length > 0">
<strong>Topics</strong>:
<span ng-repeat="topic in post.capabilities.items">
{{topic.name}}
</span>
</p>
JavaScript의 어레이(오브젝트)는 truthy 값이기 때문에 초기 검증은<p ng-if="post.capabilities.items">
항상 평가하다true
어레이가 비어 있는 경우에도 마찬가지입니다.
극복하려면null
/undefined
문제, 사용해보십시오.?
존재 여부를 확인할 연산자:
<p ng-if="post?.capabilities?.items?.length > 0">
Sidenote, Ionic Framework의 답을 찾는 사람이 이 페이지에 있다면
*ngIf
:<p *ngIf="post?.capabilities?.items?.length > 0">
제 경험으로는 HTML 템플릿에서 이것을 하는 것이 어렵다고 판단되어 TS에서 함수를 호출하여 상태를 확인하는 이벤트를 이용하기로 했습니다.true 조건이 true일 경우 HTML에서 ngIf에서 해당 변수를 사용합니다.
emptyClause(array:any) {
if (array.length === 0) {
// array empty or does not exist
this.emptyMessage=false;
}else{
this.emptyMessage=true;
}
}
HTML
<div class="row">
<form>
<div class="col-md-1 col-sm-1 col-xs-1"></div>
<div class="col-md-10 col-sm-10 col-xs-10">
<div [hidden]="emptyMessage" class="alert alert-danger">
No Clauses Have Been Identified For the Search Criteria
</div>
</div>
<div class="col-md-1 col-sm-1 col-xs-1"></div>
</form>
언급URL : https://stackoverflow.com/questions/35041618/ng-if-check-if-array-is-empty
'programing' 카테고리의 다른 글
onEnter가 React-Router에서 호출되지 않음 (0) | 2023.02.21 |
---|---|
익명 유형을 포함하는 JsonResult의 아사트 (0) | 2023.02.21 |
Material-UI에서 대화상자의 높이를 설정하려면 어떻게 해야 합니까? (0) | 2023.02.21 |
s3에서 가져온 이미지 표시 (0) | 2023.02.21 |
wp_nav_menu 변경 서브메뉴 클래스 이름? (0) | 2023.02.21 |