angular - 以角度设置页眉的问题
问题描述
我在 app.component.html 中有一个类似这样的页面,
<div class="sidenav">
<img src="../../../assets/images/control-hub-white.svg">
<a (click)="onClickHandler('Clusters')" style="color:#05a1bf" > Link1 </a>
<a (click)="onClickHandler('Checks')" >Link2</a>
<a href="/test3">Test3</a>
<a href="#contact">Contact</a>
</div>
<router-outlet></router-outlet>
<h1> {{ heading }} </h1>
我在 app.component.ts 中有一个 onClickHandler
export class AppComponent implements OnInit {
heading = 'default heading';
............
onClickHandler(heading: string){
this.heading = heading;
alert(heading);
}
在这里,当我单击链接(集群)时,我收到了预期的警报,例如集群、检查。但是,当单击链接后出现新页面时,我将标题作为默认标题。
谁能告诉我哪里出错了?
解决方案
当您再次返回此页面时,app.component 将再次启动。因此,您将再次获得“默认标题”。为了保留您的最后一个标题,请使用服务。
在 app.module.ts 的提供者中注册您的服务
应用服务.ts
import { Injectable} from '@angular/core';
@Injectable()
export class AppService {
heading: string = 'default heading';
}
app.components.ts
import {AppServices} from './app.service';
export class AppComponent implements OnInit {
constructor(private appService: AppService){}
heading: string;
onInint() {
this.heading = this.appService.heading;
}
onClickHandler(heading: string){
this.appService.heading = heading;
alert(heading);
}
}