Отзывчивый дизайн с использованием md-grid-list в angular 2
Я рассматриваю базовый пример md-grid-list в Angular 2.
Код HTML:
<md-grid-list cols="4" rowHeight="100px">
<md-grid-tile *ngFor="let tile of tiles"
[colspan]="tile.cols"
[rowspan]="tile.rows"
[style.background]="tile.color">
{{tile.text}}
</md-grid-tile>
</md-grid-list>
Код TS:
export class GridListDynamicExample {
tiles = [
{text: 'One', cols: 3, rows: 1, color: 'lightblue'},
{text: 'Two', cols: 1, rows: 2, color: 'lightgreen'},
{text: 'Three', cols: 1, rows: 1, color: 'lightpink'},
{text: 'Four', cols: 2, rows: 1, color: '#DDBDF1'},
];
}
Приведенный выше код приводит к следующему:
Как я могу сделать макет как "столбец", который является столбцом "Два", чтобы идти ниже строк (один и четыре) на меньший размер экрана, используя некоторую директиву HTML или CSS?
Angular Материал в Angular 1 имел возможность достичь, указав "md-cols-xs =" 1 "md-cols-sm =" 2 "md-cols-md =" 4 "md-cols- gt-md =" 6 "".
Ответы
Ответ 1
Это самый простой способ достижения этой цели:)
your.component.html
<md-card class="sub-category-grid" style="padding:0px;" (window:resize)="onResize($event)">
<md-grid-list cols="{{test}}" rowHeight="1:1">
<md-grid-tile *ngFor="let item of Items">
{{item.title}}
</md-grid-tile>
</md-grid-list>
</md-card>
your.component.ts
// init this var with the default number of columns
test: any = 2;
Items: any = [
{title: "title", img_src: "../../../assets/img/-samples/raketa.png", description: "Description" },
{title: "title", img_src: "../../../assets/img/-samples/raketa.png", description: "Description" },
{title: "title", img_src: "../../../assets/img/-samples/raketa.png", description: "Description" },
{title: "title", img_src: "../../../assets/img/-samples/raketa.png", description: "Description" },
{title: "title", img_src: "../../../assets/img/-samples/raketa.png", description: "Description" },
{title: "title", img_src: "../../../assets/img/-samples/raketa.png", description: "Description" },
{title: "title", img_src: "../../../assets/img/-samples/raketa.png", description: "Description" },
{title: "title", img_src: "../../../assets/img/-samples/raketa.png", description: "Description" },
{title: "title", img_src: "../../../assets/img/-samples/raketa.png", description: "Description" }
]
constructor() { }
ngOnInit() {
}
onResize(event) {
const element = event.target.innerWidth;
console.log(element);
if (element < 950) {
this.test = 2;
}
if (element > 950) {
this.test = 3;
}
if (element < 750) {
this.test = 1;
}
}
Ответ 2
Вы можете добавить директиву к своему компоненту, а затем выполнить работу в директиве следующим образом:
import { Directive, ElementRef, Input, HostListener, Output } from '@angular/core';
import * as _ from "lodash";
@Directive({ selector: '[myResponsive]' })
export class TestDirective {
@Input() tiles;
@HostListener('window:resize', ['$event'])
onResize(event) {
if (event.target.innerWidth < 980) {
_.each(this.tiles, tile => {
tile.cols = 2;
tile.rows = 1;
});
} else {
this.tiles = [
{text: 'One', cols: 3, rows: 1, color: 'lightblue'},
{text: 'Two', cols: 1, rows: 2, color: 'lightgreen'},
{text: 'Three', cols: 1, rows: 1, color: 'lightpink'},
{text: 'Four', cols: 2, rows: 1, color: '#DDBDF1'}
];
}
}
constructor(el: ElementRef) {
}
}
Вам также нужно добавить свою директиву в app.module.ts
import { TestDirective } from "./test.directive";
@NgModule({
imports: [
...
],
declarations: [
TestDirective
]
И ваш HTML должен выглядеть следующим образом
<md-grid-list cols="4" rowHeight="100px">
<md-grid-tile myResponsive [(tiles)]="tiles" *ngFor="let tile of tiles"
[colspan]="tile.cols"
[rowspan]="tile.rows"
[style.background]="tile.color">
{{tile.text}}
</md-grid-tile>
</md-grid-list>
![введите описание изображения здесь]()
Ответ 3
Как я понимаю, отзывчивая часть в настоящее время находится в проекте flex-layout. Некоторые из общих утилит из этой библиотеки будут перенесены в angular/cdk, которые уже используют. Проект Flex-layout обеспечивает наблюдение, что вы можете подписаться на получение уведомлений о изменениях точки останова - ObservableMedia. Вы также можете использовать службу MediaService (также из flex-layout), чтобы утверждать размеры окон.
Поэтому этот код может быть таким же. Обратите внимание, что я использую функцию trackBy, чтобы сохранить исходные поля при переключении.
export class AppComponent {
tiles: Array<Object>;
public columns = 4;
private subscription: Subscription;
tilesBig = [
{text: 'One', cols: 3, rows: 1, color: 'lightblue', id: 1},
{text: 'Two', cols: 1, rows: 2, color: 'lightgreen', id: 2},
{text: 'Three', cols: 1, rows: 1, color: 'lightpink', id: 3},
{text: 'Four', cols: 2, rows: 1, color: '#DDBDF1', id: 4},
];
tilesSm = [
{text: 'One', cols: 3, rows: 1, color: 'lightblue', id: 1},
{text: 'Three', cols: 1, rows: 1, color: 'lightpink', id: 3},
{text: 'Four', cols: 2, rows: 1, color: '#DDBDF1', id: 4},
{text: 'Two', cols: 3, rows: 1, color: 'lightgreen', id: 2},
];
constructor(private _media$: ObservableMedia,
private mediaService: MediaService) {
this.subscription = this._media$.subscribe((e: MediaChange) => {
this.toggle();
});
}
ngOnInit() {
this.toggle();
}
private toggle() {
const isSmall = this.mediaService.isActive('lt-md');
this.columns = isSmall ? 3 : 4;
this.tiles = isSmall ? this.tilesSm : this.tilesBig;
}
trackById(index: number, item: any): string { return item['id']; }
}
Вы можете посмотреть код https://stackblitz.com/edit/angular-t325tj?embed=1&file=app/app.component.ts
Ответ 4
Создание адаптивного дизайна в angular 4 не так просто, как в bootstrape. Чтобы сделать md-grid-list отзывчивым или изменить вид в соответствии с шириной устройства, нам нужно использовать библиотеку гибких макетов
Чтобы иметь четкое представление о том, как работа с обратными действиями работает в angular, посетите ниже ссылки
посетите http://brianflove.com/2017/05/03/responsive-angular/
demo http://run.plnkr.co/preview/cja10xr7900083b5wx6srd0r6/