【问题标题】:In angular2, how can I detect is there any ng-content?在 angular2 中,我如何检测是否有任何 ng-content?
【发布时间】:2017-09-28 19:55:33
【问题描述】:

plnkr 演示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 有可能吗?

【问题讨论】:

    标签: javascript angular angular2-template angular2-ngcontent


    【解决方案1】:

    Günter Zöchbauer 的解决方案是可以接受的,不影响使用,让组件检测到这一点,我还找到了一种更简单的方法,无需任何 json,使用 :empty

    <!-- must no content: https://css-tricks.com/almanac/selectors/e/empty/ -->
    <!--@formatter:off-->
    <div class="title"><ng-content select=".nav-title"></ng-content></div>
    <!--@formatter:on-->
    
    .title:empty {
      display: none;
    }
    

    适用于任何 html+css。

    【讨论】:

      【解决方案2】:
      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`
      }
      

      另见

      【讨论】:

        【解决方案3】:

        如果您想使用*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

        【讨论】:

        • 你能解释一下这有什么帮助吗?
        猜你喜欢
        • 2017-07-15
        • 1970-01-01
        • 2016-12-06
        • 1970-01-01
        • 2021-07-25
        • 2016-04-11
        • 1970-01-01
        • 1970-01-01
        • 2016-05-08
        相关资源
        最近更新 更多