簡體   English   中英

Angular2 - 如何執行僅限子組件的執行?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM