angular - 组件模板内的嵌套内容

标签 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”标签之间的内容,但我有点困惑如何从不同元素中获取内容并进行打印它们位于模板中我想要的位置。

提前致谢。

最佳答案

您可以像这样使用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

关于angular - 组件模板内的嵌套内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40249646/

相关文章:

angular - ngOnInit 和 ionViewWillLoad 生命周期钩子(Hook)/事件之间的关联

javascript - Angular 2 -bypassSecurityTrustHtml 以及bypassSecurityTrustScript

angular - ngIf - else 与两个 ngIf 条件

Angular 2,无法从另一个组件访问一个组件中的变量

Angular 2 找不到在我的功能模块中声明的组件

unit-testing - 如何在 Angular2 中监视服务调用

css - Angular2 包含 - 将 css 应用于子元素类

javascript - 以 Angular 4 过滤给定数组而不使用另一个数组并将其显示在同一组件中

angular - 内部带有 *ngIf 的模板,更改模型后不起作用

javascript - 根组件在路由器导出中呈现自己