我正在尝试根据条件有条件地在
<ng-content>
内显示 <div>
。然而,由于某种原因,即使条件为真,<ng-content>
内的<div>
也永远不会显示。内容在 @else
块下正确渲染,但是当满足 @if
条件时,<div>
中的内容不可见。
这是代码的简化版本:
<app-header />
<div class="container">
@if (innerWidth <= 768) {
@if (open()) {
<div class="container2" style="width: 450px; z-index: 15;">
<ng-content />
</div>
}
} @else {
<ng-content />
}
<!-- <app-vehicles /> -->
<!-- <app-tracking-data /> -->
<app-map />
</div>
预期行为: 当
<ng-content>
和 @if
返回 true 时,应显示 innerWidth <= 768
块内的 open()
。
实际行为: 条件
<ng-content>
中的 <div>
永远不会显示,而 @else
块中的内容按预期工作。
您面临 XY 问题。您尝试将媒体查询的解决方案应用于容器而不是文档。由于媒体查询无法以这种方式工作,因此您尝试动态操作 DOM 作为解决方案。
我不会解决你手头的问题,而是解决你的实际问题,甚至不需要你的尝试。
如上所述,媒体查询仅适用于整个文档或屏幕。如果您想要专门针对块级元素进行 CSS 查询,则必须使用 container query:
@container (max-width: 768px) {
.container {
width: 450px;
z-index-15;
}
}
不鼓励根据文档在条件语句中显示
ng-content
。
而是使用
ContentChild
获取数据并显示它。
import {
Component,
contentChild,
ContentChild,
signal,
TemplateRef,
Signal,
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { bootstrapApplication } from '@angular/platform-browser';
@Component({
selector: 'app-child',
standalone: true,
imports: [CommonModule],
template: `
<div class="container">
@if (open()) {
<div class="container2" style="background-color: red;width: 450px; z-index: 15;">
<ng-container *ngTemplateOutlet="content()"></ng-container >
</div>
} @else {
<ng-container *ngTemplateOutlet="content()"></ng-container >
}
</div>
`,
})
export class Child {
content: Signal<any> = contentChild('content');
name = 'Angular';
open = signal(true);
ngAfterContentInit() {
setInterval(() => {
this.open.set(!this.open());
}, 1000);
console.log(this.content);
}
}
@Component({
selector: 'app-root',
standalone: true,
imports: [Child],
template: `
<app-child>
<ng-template #content>
<h1>Hello from {{ name }}!</h1>
<a target="_blank" href="https://angular.dev/overview">
Learn more about Angular
</a>
</ng-template>
</app-child>
`,
})
export class App {
name = 'Angular';
}
bootstrapApplication(App);