angular-docs-cn/public/docs/_examples/router/ts/app/crisis-center/crisis-detail.component.ts

117 lines
2.9 KiB
TypeScript

// #docplaster
// #docregion
import { Component, OnInit, HostBinding,
trigger, transition,
animate, style, state } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Crisis } from './crisis.service';
import { DialogService } from '../dialog.service';
@Component({
template: `
<div *ngIf="crisis">
<h3>"{{ editName }}"</h3>
<div>
<label>Id: </label>{{ crisis.id }}</div>
<div>
<label>Name: </label>
<input [(ngModel)]="editName" placeholder="name"/>
</div>
<p>
<button (click)="save()">Save</button>
<button (click)="cancel()">Cancel</button>
</p>
</div>
`,
styles: ['input {width: 20em}'],
// #enddocregion template
animations: [
trigger('routeAnimation', [
state('*',
style({
opacity: 1,
transform: 'translateX(0)'
})
),
transition(':enter', [
style({
opacity: 0,
transform: 'translateX(-100%)'
}),
animate('0.2s ease-in')
]),
transition(':leave', [
animate('0.5s ease-out', style({
opacity: 0,
transform: 'translateY(100%)'
}))
])
])
]
})
export class CrisisDetailComponent implements OnInit {
@HostBinding('@routeAnimation') get routeAnimation() {
return true;
}
@HostBinding('style.display') get display() {
return 'block';
}
@HostBinding('style.position') get position() {
return 'absolute';
}
crisis: Crisis;
editName: string;
constructor(
private route: ActivatedRoute,
private router: Router,
public dialogService: DialogService
) {}
// #docregion crisis-detail-resolve
ngOnInit() {
this.route.data
.subscribe((data: { crisis: Crisis }) => {
this.editName = data.crisis.name;
this.crisis = data.crisis;
});
}
// #enddocregion crisis-detail-resolve
cancel() {
this.gotoCrises();
}
save() {
this.crisis.name = this.editName;
this.gotoCrises();
}
canDeactivate(): Promise<boolean> | boolean {
// Allow synchronous navigation (`true`) if no crisis or the crisis is unchanged
if (!this.crisis || this.crisis.name === this.editName) {
return true;
}
// Otherwise ask the user with the dialog service and return its
// promise which resolves to true or false when the user decides
return this.dialogService.confirm('Discard changes?');
}
// #docregion gotoCrises
gotoCrises() {
let crisisId = this.crisis ? this.crisis.id : null;
// Pass along the crisis id if available
// so that the CrisisListComponent can select that crisis.
// Add a totally useless `foo` parameter for kicks.
// #docregion gotoCrises-navigate
// Relative navigation back to the crises
this.router.navigate(['../', { id: crisisId, foo: 'foo' }], { relativeTo: this.route });
// #enddocregion gotoCrises-navigate
}
// #enddocregion gotoCrises
}