Kurs Angular · Moduł 13: UI i stylowanie
Responsive Design
W tej lekcji4
Jak zamek dostosowuje obronę do różnych ataków, tak UI musi dostosować się do różnych urządzeń.
Media Queries
// mixins.scss
@mixin mobile {
@media (max-width: 599px) { @content; }
}
@mixin tablet {
@media (min-width: 600px) and (max-width: 959px) { @content; }
}
@mixin desktop {
@media (min-width: 960px) { @content; }
}
// Użycie
.samurai-grid {
display: grid;
gap: 1rem;
@include mobile {
grid-template-columns: 1fr;
}
@include tablet {
grid-template-columns: repeat(2, 1fr);
}
@include desktop {
grid-template-columns: repeat(4, 1fr);
}
}CDK BreakpointObserver
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';
@Component({
template: `
@if (isMobile()) {
<app-mobile-nav />
} @else {
<app-desktop-nav />
}
<div [class]="layoutClass()">
<ng-content />
</div>
`
})
export class ResponsiveLayoutComponent {
private breakpointObserver = inject(BreakpointObserver);
isMobile = toSignal(
this.breakpointObserver.observe([Breakpoints.Handset]).pipe(
map(result => result.matches)
),
{ initialValue: false }
);
layoutClass = computed(() => this.isMobile() ? 'mobile-layout' : 'desktop-layout');
}Flexbox Layouts
@Component({
template: `
<div class="flex-container">
<aside class="sidebar">Menu</aside>
<main class="content">
<ng-content />
</main>
</div>
`,
styles: [`
.flex-container {
display: flex;
flex-wrap: wrap;
min-height: 100vh;
}
.sidebar {
flex: 0 0 250px;
}
.content {
flex: 1;
min-width: 0; /* Ważne dla overflow */
}
@media (max-width: 768px) {
.sidebar {
flex: 0 0 100%;
order: 2;
}
.content {
order: 1;
}
}
`]
})
export class LayoutComponent {}Container Queries (CSS)
// Nowoczesne podejście
.card-container {
container-type: inline-size;
container-name: card;
}
.card {
@container card (min-width: 400px) {
display: grid;
grid-template-columns: 1fr 2fr;
}
@container card (max-width: 399px) {
display: block;
}
}Widzisz błąd w tej lekcji?
Sprawdź się
Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.
1. Do czego służy BreakpointObserver z @angular/cdk/layout?
2. Której funkcji użyto w lekcji, aby zamienić Observable z BreakpointObserver na sygnał?
To 2 z 3 pytań do tej lekcji. Pozostałe rozwiążesz w grze.
Zadania praktyczne w grze
- Układanie w poziomie
Ułóż w jednej linii nagłówek media query dla urządzeń mobilnych.
- Edytor kodu
Uzupełnij komponent reagujący na rozmiar ekranu.
- Układanie w pionie
Uporządkuj breakpointy z lekcji od najmniejszego do największego ekranu.