Angular 2에서 확인하는 방법 비었다?
구성 요소가 있다고 가정합니다.
@Component({
selector: 'MyContainer',
template: `
<div class="container">
<!-- some html skipped -->
<ng-content></ng-content>
<span *ngIf="????">Display this if ng-content is empty!</span>
<!-- some html skipped -->
</div>`
})
export class MyContainer {
}
이제이 <ng-content>
구성 요소가 비어있는 경우 일부 기본 콘텐츠를 표시하고 싶습니다 . DOM에 직접 액세스하지 않고 쉽게 할 수있는 방법이 있습니까?
ng-content
a와 같은 HTML 요소를 래핑 div
하여 로컬 참조를 가져온 다음 ngIf
표현식을 다음과 같이 바인딩합니다 ref.children.length == 0
.
template: `<div #ref><ng-content></ng-content></div>
<span *ngIf="ref.nativeElement.childNodes.length == 0">
Display this if ng-content is empty!
</span>`
@pixelbits 답변에 누락 된 부분이 있습니다. children
부모 템플릿의 줄 바꿈이나 공백으로 인해 children
빈 텍스트 \ 줄 바꿈이있는 요소 가 발생하기 때문에 속성 뿐만 아니라 확인해야합니다 . 더 나은이 확인 .innerHTML
하고 .trim()
그것.
작업 예 :
<span #ref><ng-content></ng-content></span>
<span *ngIf="!ref.innerHTML.trim()">
Content if empty
</span>
콘텐츠를 삽입 할 때 참조 변수를 추가합니다.
<div #content>Some Content</div>
구성 요소 클래스에서 @ContentChild ()를 사용하여 삽입 된 콘텐츠에 대한 참조를 가져옵니다.
@ContentChild('content') content: ElementRef;
따라서 구성 요소 템플릿에서 콘텐츠 변수에 값이 있는지 확인할 수 있습니다.
<div>
<ng-content></ng-content>
<span *ngIf="!content">
Display this if ng-content is empty!
</span>
</div>
다음은 CSS 솔루션입니다. ng-content에 아무것도 설정되지 않은 경우 기본 구성 요소를 제공 할 수 있습니다. 제 경우에는 형제 자매이므로 이렇게 해결할 수 있습니다.
IE 9 이후 및 부분적으로 IE7 / 8 이후 호환 : https://caniuse.com/#feat=css-sel3
HTML
<div class="my-custom-component-content-wrapper">
<ng-content select="my-custom-component"></ng-content>
</div>
<my-custom-component>
This shows something default.
</my-custom-component>
CSS
.my-custom-component-content-wrapper:not(:empty) + my-custom-component {
display: none;
}
주사 elementRef: ElementRef
하고 elementRef.nativeElement
아이가 있는지 확인하십시오 . 이것은 encapsulation: ViewEncapsulation.Native
.
<ng-content>
태그를 감싸고 자녀가 있는지 확인하십시오. 이것은 encapsulation: ViewEncapsulation.Native
.
<div #contentWrapper>
<ng-content></ng-content>
</div>
자녀가 있는지 확인하십시오.
@ViewChild('contentWrapper') contentWrapper;
ngAfterViewInit() {
contentWrapper.nativeElement.childNodes...
}
(검증되지 않은)
제 경우에는 빈 ng-content의 부모를 숨겨야합니다.
<span class="ml-1 wrapper">
<ng-content>
</ng-content>
</span>
간단한 CSS 작동 :
.wrapper {
display: inline-block;
&:empty {
display: none;
}
}
참고 URL : https://stackoverflow.com/questions/35107211/in-angular-2-how-to-check-whether-ng-content-is-empty
'Development Tip' 카테고리의 다른 글
Java 프로그램 내에서 방금 시작한 프로세스의 PID를 얻는 방법은 무엇입니까? (0) | 2020.11.14 |
---|---|
WebApi에 SSL이 필요합니까? (0) | 2020.11.14 |
VS Code에서 Git 누락 – 소스 제어 공급자 없음 (0) | 2020.11.14 |
JavaScript 스포이드 (마우스 커서 아래의 픽셀 색상 표시) (0) | 2020.11.14 |
PHP에서 문자열의 최대 길이는 얼마입니까? (0) | 2020.11.14 |