这是我的父组件 html
<app-card>
<div class="body">This is body</div>
<div class="title">This is title</div>
</app-card>
Run Code Online (Sandbox Code Playgroud)
这是我的 CardComponent
<div class="card">
<ng-content select=".title"></ng-content>
<ng-content select=".body"></ng-content>
</div>
Run Code Online (Sandbox Code Playgroud)
所以我想访问这个元素(<div class="body">This is body</div>
CardComponent 中的这个元素 ( ),如果它是一个组件,我可以通过 ContentChild 访问它,但是如何访问它?
我尝试使用模板变量(在 ContentChild 中传递变量名称)并尝试从 ngAfterContentInit 获取未定义的形式访问它
menu
和 maincontent
是特定于模块的,因此我使用的是插槽。换句话说:五分之一的不同可能的父组件使用这个组件并提供main
内容和一个(单独不同的)menu
,使用角度内容投影。 <ng-template #menu><ng-content select="[slot='menu']"></ng-content></ng-template>
<ng-template #content><ng-content select="[slot='content']"></ng-content></ng-template>
<section *ngIf="landscape">
<div class="global-ui-top">
<ng-container *ngTemplateOutlet="menu"></ng-container> // 1st
</div>
<some-main-content>
<ng-container *ngTemplateOutlet="content"></ng-container>
</some-main-content>
<div class="global-ui-bottom">
<ng-container *ngTemplateOutlet="menu"></ng-container> // 2nd
</div>
</section>
// portrait mode
<section *ngIf="!landscape">
... pretty similar to above, also 2× menu, 1× content...
Run Code Online (Sandbox Code Playgroud)
A <ng-container *ngTemplateOutlet="menu"></ng-container> A
B <ng-container *ngTemplateOutlet="menu"></ng-container> B
Run Code Online (Sandbox Code Playgroud)
...然而,插槽 get 只在最后一次“选择一次”(两个 A 之间的标签保持为空)。换句话说,我的第一个.global-ui-top
仍然是空的。
注意:ng-detour
第 …
我试图在带有 template-outlet 的 mat-select 中传递 #tmp,但无法显示选择选项。下面是我的代码和 stackblitz 的链接
<mat-form-field>
<mat-select
[ngModel]="selectedFoods"
(ngModelChane)="selectedFoods" placeholder="Favorite food" multiple>
<ng-container *ngFor="let food of allfoods"
[ngTemplateOutlet]="tmp"
[ngTemplateOutletContext]="{ $implicit: food}">
</ng-container>
</mat-select>
</mat-form-field>
<ng-template #tmp let-food>
<mat-option [value]="food.value">
{{food.viewValue}}
</mat-option>
</ng-template>
Run Code Online (Sandbox Code Playgroud)
在内容投影场景中,我有以下场景:
// my-component.ts
@ContentChildren(SelectOption) selectOptions: QueryList<SelectOption>;
...
ngAfterContentInit() {
this.selectOptions.forEach((selectOption, i) => {
selectOption.index = i;
});
}
Run Code Online (Sandbox Code Playgroud)
假设模板具有以下结构:
<ng-content select="select-option"></ng-content>
Run Code Online (Sandbox Code Playgroud)
我尝试通过以下方式模拟测试,但找不到允许我添加子组件的“添加”方法。
// my-component.spec.ts
component.selectOptions = {} as QueryList<SelectOption>;
Run Code Online (Sandbox Code Playgroud)
但我不知道如何在单元测试场景(不是集成测试)中添加预计的组件
unit-testing mocking jasmine angular angular-content-projection