【发布时间】:2021-04-20 19:49:01
【问题描述】:
目前我试图将第三个组件投影到一个子组件中,该子组件被投影在ngFor 循环内(在子组件内),但是每当我使用查询列表的索引更改或设置投影内容中的某些属性时在父组件中 (ViewChildren('#thirdComponent')) 在父级中所有子级的投影内容都显示相同的变化。有什么合适的方法吗?
是不是因为子组件的内容投影位置重复了select属性绑定。子组件的投影是在一次打开一个或多个面板的手风琴内完成的。
@Component({
selector: "my-app",
template: `
<child-comp #child>
<ng-container selected>
<some-other-comp #someOtherComp></some-other-comp>
</ng-container>
</child-comp>
`,
styleUrls: ["./app.component.css"]
})
export class AppComponent implements AfterViewInit {
h = 0;
i = 1;
j = 2;
k = 3;
@ViewChildren("someOtherComp") otherCompList: QueryList<SomeOtherComponent>;
ngAfterViewInit(): void {
this.otherCompList.toArray()[this.h].prop = this.h;
// below will result in undefined due to QueryList of size 1
// this.otherCompList.toArray()[this.i].prop = this.i;
// this.otherCompList.toArray()[this.j].prop = this.j;
// this.otherCompList.toArray()[this.k].prop = this.k;
}
}
@Component({
selector: "child-comp",
template: `
<div *ngFor="let value of [1, 2, 3]; let i = index">
<!-- if ngIf is removed than only the last projection is diplayed -->
<div *ngIf="i === 0">
<ng-content select="[selected]"> </ng-content>
</div>
</div>
`,
styleUrls: ["./app.component.css"]
})
export class ChildComponent {}
@Component({
selector: "some-other-comp",
template: `
<p>{{ prop }}</p>
`,
styleUrls: ["./app.component.css"]
})
export class SomeOtherComponent {
prop: any;
}
【问题讨论】:
标签: javascript angular