我正在开发应用程序,我需要执行以下操作-当我更改select中的选项时,应该有一条通往另一个组件的路线(我想它已经完成了),但是当我手动更改url时,选择菜单也应该更改。
header.component.html
<select id="city" [(ngModel)]="dataFromService"
(ngModelChange)="navigateTo(dataFromService)">
<option value='' disabled>Choose city</option>
<option *ngFor="let city of cities" [(value)]="city.name">{{ city.name
}}</option>
</select>
header.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { CityToggleService } from '../../cityToggle.service';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.sass']
})
export class HeaderComponent implements OnInit {
dataFromService: string;
cities: { id: number, name: string }[] = [];
public value;
constructor( private cityToggleService: CityToggleService,
private router: Router ) { }
navigateTo(dataFromService) {
this.cityToggleService.navigateTo(dataFromService);
}
ngOnInit() {
this.cities = this.cityToggleService.getCities();
this.dataFromService =
this.cityToggleService.getSelectedItem(this.value);
}
}
cityToggleService.ts
import { Input } from '@angular/core';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
@Injectable()
export class CityToggleService {
constructor( private router: Router ) {}
public selectedItem = '';
private cities = [
{ id: 1, name: 'City1' },
{ id: 2, name: 'City2' },
{ id: 3, name: 'City3' },
{ id: 4, name: 'City4' },
{ id: 5, name: 'City5' },
];
public city: { id: number, name: string };
getSelectedItem(name: string) {
const item = this.cities.find(
(s) => {
return s.name === name;
}
);
return item;
}
getCities() {
return this.cities;
}
navigateTo(selectedItem) {
this.router.navigate(['stages', selectedItem]);
}
}
我希望当我更改URL时,选择菜单也会执行相同的操作。 site / City1 =>选择“ City1”位置
答案 0 :(得分:0)
使用Angular:
export class MyContainer {
constructor(private _router: Router) {
router.events.subscribe(routeEvent => {
if (val instanceof NavigationEnd) {
...do something
}
}
}
}
使用JavaScript:
window.onhashchange = function(e) {
// do something after hashchange
}
要使用JavaScript但在较旧的浏览器中检测路线更改,则需要间隔检查window.location.href
。