簡體   English   中英

如何獲得ng-content選擇過濾器以處理投影的模板內容?

[英]How can I get an ng-content select filter to work with projected template content?

我有一個用於呈現列表的List組件。 (嗯,我沒有,但是我試圖將我的問題分解成一個易於理解的點頭例子)。

List組件的模板具有一個或多個ListItem組件,這些組件允許定義列表項,如下所示:

<app-list>
  <app-list-item text='foo'></app-list-item>
  <app-list-item text='bar'></app-list-item>
</app-list>

...應呈現為:

  • FOO
  • 酒吧

我還擁有一個“ Reminder組件,該組件利用了List組件。 Reminder組件具有一個deadline屬性,並且使用我們之前看到的一個或多個ListItem組件,在該組件的模板中定義了在該截止日期之前要做的事情的列表:

<app-reminder deadline='Today'>
  <app-list-item text='foo'></app-list-item>
  <app-list-item text='bar'></app-list-item>
</app-reminder>

這應該表示為:

請記住在今天之前執行以下操作:

  • FOO
  • 酒吧

List組件非常簡單:

@Component({
  selector: 'app-list',
  template: `
    <ul>
      <ng-content></ng-content>
    </ul>
  `
})
export class ListComponent{
  @ContentChildren(ListItemComponent) public readonly items: QueryList<ListItemComponent>;
}

ListItem組件甚至更簡單:

@Component({
  selector: 'app-list-item',
  template: '<li>{{text}}</li>'
})
export class ListItemComponent {
  @Input() public text;
}

最后, Reminder組件也非常簡單:

@Component({
  selector: 'app-reminder',
  template: `
    <h2>Remeber to do the following by {{deadline}}</h2>
    <app-list>
      <ng-content></ng-content>
    </app-list>
  `
})
export class ReminderComponent {
  @Input() public deadline: string;
}

將這些組件與上面顯示的模板片段一起使用時效果很好。 您可以在此StackBlitz中看到這一點

現在到問題的要點。 List組件和Reminder組件都使用<ng-content> 在這兩種情況下,我們都不希望將所有內容投影到列表中,而只是將<app-list-item>元素投影到列表中。

如果我像這樣更改Reminder組件模板中的<ng-content>標簽:

<ng-content select='app-list-item'></ng-content>

...然后該組件仍然可以正常工作,並在其模板中排除了我們想要的任何其他內容。

如果我對List組件的模板中的<ng-content>標記進行了相同的更改,那么這也適用於像這樣的簡單模板:

<app-list>
  <app-list-item text='foo'></app-list-item>
  <app-list-item text='bar'></app-list-item>
  <h1>EXCLUDE ME</h1>
</app-list>

但是 ,最后一次更改(在List組件模板的<ng-content>元素中添加select過濾器)使Reminder組件無法正常工作。 提醒中未呈現任何列表項。

我想這可能是因為Reminder組件的模板呈現的List組件看到的是呈現的內容( <li>標記)而不是模板內容( <app-list-item>標記)。

似乎我在這里有一個不愉快的選擇-我不能限制List組件將呈現的內容的類型(在這種情況下,可能會包括任何舊的垃圾),或者在創建時失去使用List組件的能力其他組件。

還是我錯過了什么? 還有另一種方法嗎?

我設法通過使用ngProjectAs解決了這個問題

reminder.component.ts

@Component({
  selector: 'app-reminder',
  template: `
    <h2>Remeber to do the following by {{deadline}}</h2>
    <app-list>
      <ng-container ngProjectAs="'app-list-item'">
        <ng-content select='app-list-item'></ng-content>
      </ng-container>
    </app-list>
  `
})
export class ReminderComponent {
  @Input() public deadline: string;
}

這是StackBlitz演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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