ng g s storage
storage.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class StorageService {
text = '初始值';
color = 'gray';
}
app.component.html、app.component.css、app.component.ts
<button (click)="storageService.text='全局改变后的值';storageService.color='red'">改变全局变量(文字变红色)</button>
<h1 [attr.color]="storageService.color">{{storageService.text}}</h1>
<app-other></app-other>
________________________________________________________________________________
[color="gray"] {
color: gray;
}
[color="red"] {
color: red;
}
________________________________________________________________________________
import { Component } from '@angular/core';
import { StorageService } from './services/storage.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(public storageService: StorageService,) {}
}
components/other.component.html、components/other.component.css、components/other.component.ts
<p>其他组件:</p>
<h1 [attr.color]="storageService.color">{{storageService.text}}</h1>
________________________________________________________________________________
[color="gray"] {
color: gray;
}
[color="red"] {
color: red;
}
________________________________________________________________________________
import { Component } from '@angular/core';
import { StorageService } from '../../services/storage.service';
@Component({
selector: 'app-other',
templateUrl: './other.component.html',
styleUrls: ['./other.component.css']
})
export class OtherComponent {
constructor(public storageService: StorageService,) {}
}
点击按钮后