在angular2中,如何检测是否存在任何ng内容?

时间:2017-05-01 11:35:38

标签: javascript angular angular2-template angular2-ngcontent

plnkr demo here

@Component({
  selector: 'my-demo',
  template: `This is <ng-content select=".content"></ng-content>`
})
export class DemoComponent { name = 'Angular'; }

@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>
    <my-demo><div class="content">In Content</div></my-demo>
  `
})
export class AppComponent { name = 'Angular'; }

我希望条件ng-content,例如

<ng-template *ngIf='hasContent(".content"); else noContent'>
This is <ng-content select=".content"></ng-content>
</ng-template>
<ng-template #noContent>No content</ng-template>

有可能在angular2?

2 个答案:

答案 0 :(得分:0)

template: `This is <span #wrapper>
  <ng-content select=".content"></ng-content>
  </span>`
@ViewChild('wrapper') wrapper:ElementRef;

ngAfterContentInit() {
    console.log(this.wrapper.innerHTML); // or `wrapper.text`
}

另见

答案 1 :(得分:0)

如果你想使用带有*ngIfelse的条件语句,那是可能的

@Component({
  selector: 'my-demo',
  template: `<div *ngIf='content; else noContent'>
This is <ng-content select=".content"></ng-content>
</div>

<ng-template #noContent>No content</ng-template>`
})
export class DemoComponent { name = 'Angular'; content = true}

Demo