组件模板中的嵌套内容

时间:2016-10-25 21:02:54

标签: angular angular2-template angular2-components

我有一个名为'select-other'的组件,里面我有两个元素需要获取内容并在我的'select-other'组件模板中打印。

HTML

<select-other>
  <options>
    <option value="one">One</option>
    <option value="two">Two</option>
    <option value="three">Three</option>
  </options>

  <other>
    <input>
    <button></button>
  </other>
</select-other>

组件装饰器

@Component({
  selector: 'select-other',
  template: `
    <select
      *ngIf="select !== 'other'"
      [(ngModel)]="select"
      class="form-control"
    >
      // CONTENT FROM INSIDE <OPTIONS> HERE
      <option
        value="other"
      >Other</option>
    </select>
    // CONTENT FROM INSIDE <OTHER> HERE
  `
})

据我所知,我可以在模板中使用'ng-content'来打印我的'select-other'标签之间的内容,但是我有点迷惑如何从内容中获取不同元素的内容并打印他们在模板中我想要的地方。

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以像这样使用ng-content内容投影:

@Component({
    selector: 'select-other',
    template: `
       <select
       *ngIf="select !== 'other'"
       [(ngModel)]="select"
       class="form-control">
           // CONTENT FROM INSIDE <OPTIONS> HERE
           <ng-content select="options"></ng-content>

           <option value="other">Other</option>
       </select>
       // CONTENT FROM INSIDE <OTHER> HERE
       <ng-content select="other"></ng-content>
    `
})

因此,您可以通过其父元素选择器选择所需的内容。 有关此here

的更多信息
相关问题