【发布时间】:2018-12-09 02:41:01
【问题描述】:
我要求组件上的搜索功能必须触发“历史点”,以便用户可以单击浏览器中的后退按钮并向后导航不同的结果。最终,他们还希望能够导航到一个单独的组件(项目详细信息),并且仍然能够单击返回并返回到他们搜索的项目列表。想想搜索订单、按日期和状态过滤、查看列表,然后单击“订单详细信息”。您将被带到订单详细信息组件,然后单击返回将带您回到过滤后的订单列表。
按照我的理解,这应该可以通过router 和location 的某种组合来实现?
我尝试实现这个非常简单的示例,每次在选择列表中选择一个新值时都应该设置一个新的历史记录点,但到目前为止我没有尝试过任何工作。
StackBlitx 链接:https://stackblitz.com/edit/angular-1vfhwv?file=src%2Fapp%2Fhome%2Fhome.component.ts
组件 TS
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Location } from '@angular/common';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
ngOnInit() {
}
constructor(
private router: Router,
private location: Location
){}
colors: string[] = ['Red','Green','Blue', 'Purple', 'Black', 'White'];
selectedColor = this.colors[0];
selectedColors: string[] = [this.selectedColor];
selectedColorChanged(event)
{
this.selectedColors.push(event.target.value);
var uniqueValue = this.newGuid();
//this.router.navigateByUrl("");
this.location.replaceState("", uniqueValue);
}
back(){
this.location.back();
}
newGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
}
组件 HTML
<select [(ngModel)]="selectedColor" (change)="selectedColorChanged($event)">
<option *ngFor="let c of colors">{{c}}</option>
</select>
<p>
Selected Color: {{selectedColor}}
</p>
<div>
Selected Colors:
<div *ngFor="let c of selectedColors">
{{c}}
</div>
</div>
【问题讨论】:
标签: angular html5-history