[英]Angular2 - How to Do Child-Component-Only Enforcement?
在Angular2中,假設我有兩個組件,一個列表和一個列表項。 我希望列表項只能放在列表中:
<my-list>
<my-list-item>Foo</my-list-item>
</my-list>
有沒有辦法在TypeScript中強制執行此操作?
在my-list-item
組件中執行此操作
而my-list-item
將不會呈現,如果它不是里面my-list
import {Component, ElementRef} from 'angular2/core';
@Component({
selector: 'my-list-item',
template: '<div *ngIf="insideMyList"> <ng-content></ng-content> </div>'
})
export class MyListItem{
public insideMyList: boolean = false;
constructor(elementRef: ElementRef) {
if(elementRef['internalElement'].parent.nativeElement.localName == 'my-list')
{
//do other stuff here
this.insideMyList = true;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.