<div class="min-h-screen flex flex-col">
<app-header></app-header>
<div class="flex-grow">
<router-outlet></router-outlet>
</div>
<app-footer></app-footer>
</div>
我有这样的默认布局结构。但是当我访问例如 app-home 组件时,它的高度和宽度为 0。使用 :host 的方法可能不好,因为我需要将其应用于将创建的每个组件。父 div(这一个 div class="flex-grow")具有完整的宽度和高度。
如果您的目标浏览器支持
display:grid
,那么使用它来解决您的问题。
以下代码片段利用 Angular 路由的行为将路由组件作为 DOM 中
router-outlet
元素的同级元素插入。
.app-content {
/*
The available height will be distributed equally between children of this element.
Children with display:none won't be considered.
*/
display: grid;
}
.app-content router-outlet {
display: none;
}
/*
Some styles to actually see the elements in the example.
Not relevant to the problem at hand
*/
app-header,
app-footer {
display: block;
height: 60px;
background-color: gray;
}
app-some-content {
display: block;
background: red;
}
body {
margin: 0;
padding: 0;
}
.min-h-screen {
min-height: 100vh
}
.flex {
display: flex;
}
.flex-col {
flex-direction: column;
}
.flex-grow {
flex-grow: 1;
}
<div class="min-h-screen flex flex-col">
<app-header>Header</app-header>
<div class="flex-grow app-content">
<router-outlet></router-outlet>
<!-- Angular inserts the routed component right after the router-outlet element -->
<app-some-content>Content</app-some-content>
</div>
<app-footer>Footer</app-footer>
</div>