如果需要知道是否提供投影,如何实现?
@Component({
template: `{{ projections().length }}`
})
class MyComponent {
projections = contentChildren('*'); // pseudocode, '*' - fake selector
}
有没有正确的方法来观察所有投影,尽管有一种类型?
我们只需添加一个 elementRef
#test
并查询该值,这将为我们提供两个值!
main.ts
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { ChildComponent } from './app/child/child.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [ChildComponent],
template: `
<app-child>
<h1 #test>Hello from {{ name }}!</h1>
<h1 #test>Learn more about Angular</h1>
</app-child>
`,
})
export class App {
name = 'Angular';
}
bootstrapApplication(App);
child.ts
import {
Component,
ElementRef,
computed,
contentChildren,
} from '@angular/core';
@Component({
selector: 'app-child',
standalone: true,
imports: [],
template: `
<ng-content/>
{{ projections().length }}
`,
})
export class ChildComponent {
projections = contentChildren('test');
}
我们还可以查询内部元素,访问内部值!
儿童.ts
import {
Component,
ElementRef,
computed,
contentChildren,
} from '@angular/core';
@Component({
selector: 'app-child',
standalone: true,
imports: [],
template: `
<ng-content/>
{{ innerProjections().length }}
`,
})
export class ChildComponent {
projections = contentChildren('test', { descendants: true });
innerProjections = computed(() => {
const projection: ElementRef<any> = this.projections()?.at(
0
) as ElementRef<any>;
return projection?.nativeElement?.children;
});
ngAfterContentInit() {
console.log(this.projections());
}
}
main.ts
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { ChildComponent } from './app/child/child.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [ChildComponent],
template: `
<app-child>
<div #test>
<h1>Hello from {{ name }}!</h1>
<h1>Learn more about Angular</h1>
</div>
</app-child>
`,
})
export class App {
name = 'Angular';
}
bootstrapApplication(App);