【发布时间】:2018-11-02 21:26:19
【问题描述】:
我正在使用 Angular Material 构建一个 Angular 7 网站(我是网络开发的新手)。 我被一些看似微不足道的东西困住了:在我的 products.component 中,我想使用Angular Material Button Toggle 在网格视图(默认)和我的产品的列表视图之间切换。我们在许多电子商务中看到的一个功能。这是我的简化代码:
<mat-button-toggle-group value="grid">
<mat-button-toggle value="grid">
<mat-icon>view_module</mat-icon>
</mat-button-toggle>
<mat-button-toggle value="list">
<mat-icon>view_list</mat-icon>
</mat-button-toggle>
</mat-button-toggle-group>
产品的网格视图(必须是默认视图):
<div *ngFor="let product of products">
<a>
...
</a>
</div>
产品列表视图:
<div>
<ul>
<li *ngFor="let product of products"></li>
</ul>
</div>
我已经尝试过 ViewChild、NgModel、NgSwitch、TemplateRef 等各种解决方案...我遗漏了一些东西,我在这方面花了很多时间,所以我依赖你!提前致谢
编辑:没有实现路由,我的 app.component 看起来像这样:
<app-header>
<app-products>
<app-footer>
我的 products.component 是这样构建的(简化)
<mat-toolbar>
<mat-button-group>
...
</mat-button-group>
</mat-toolbar>
<div class="container">
<div *ngFor="let product of products">
<a>
...
</a>
</div>
<div>
<ul>
<li *ngFor="let product of products">
...
</li>
</ul>
</div>
</div>
所有在一个组件中。为网格视图创建两个子组件,列表不是要走的路,对吧?无论如何,我已经尝试过将 div.container 中的代码移动到另一个我已经尝试过的组件中:
@Component({
templateUrl:
`
<div #listTemplate>
<p>List View</p>
</div>
<div #gridTemplate>
<p>Grid View</p>
</div>
`
})
export class ... {
@ViewChild('listTemplate') listTemplate: TemplateRef<any>;
@ViewChild('gridTemplate') gridTemplate: TemplateRef<any>;
}
但我无法通过单击按钮切换来绑定它。 Material Button Toggle 在单击时会发出一个更改事件,因此它应该让我使用 ngModel。我尝试过这样的事情:
<mat-toolbar>
<mat-button-group>
<mat-button-toggle (click)="change(view.value)">...</mat-button-toggle>
<mat-button-toggle (click)="change(view.value)">...</mat-button-toggle>
</mat-button-group>
</mat-toolbar>
<div class="container">
<div *ngFor="let product of products" [(ngModel)]="grid" #view>
<a>
...
</a>
</div>
<div [(ngModel)]="list" #view>
<ul>
<li *ngFor="let product of products">
...
</li>
</ul>
</div>
</div>
但不知道如何使用 change(value) 插入适当的模板。 ngTemplateOutlet 可能是一个合适的解决方案,但我还没有尝试过。显然我对这个 Angular 特性缺乏一些了解,但我已经成功地在我的站点中实现了其他东西,所以我想实现这一点。
【问题讨论】:
-
您可以将您的实验添加到您的问题中吗?事实上,不同的显示和按钮切换组之间没有任何联系。
-
你能多介绍一下你是如何组织一切的吗?组件是如何构建的?它是单个组件吗?你用什么来存储你从切换中获得的值?
-
我已经编辑了我的帖子