在Angular 9中,要从另一个同级组件中更改变量,可以通过以下步骤实现:
ng generate service shared
这将在src/app目录下创建一个名为shared的文件夹,并在其中生成一个shared.service.ts文件。
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SharedService {
private sharedVariable: string;
constructor() { }
setSharedVariable(value: string) {
this.sharedVariable = value;
}
getSharedVariable() {
return this.sharedVariable;
}
}
import { Component } from '@angular/core';
import { SharedService } from '../shared/shared.service';
@Component({
selector: 'app-component-a',
template: `
<button (click)="changeVariable()">Change Variable</button>
`
})
export class ComponentA {
constructor(private sharedService: SharedService) { }
changeVariable() {
this.sharedService.setSharedVariable('New Value');
}
}
import { Component } from '@angular/core';
import { SharedService } from '../shared/shared.service';
@Component({
selector: 'app-component-b',
template: `
<p>{{ sharedVariable }}</p>
`
})
export class ComponentB {
sharedVariable: string;
constructor(private sharedService: SharedService) {
this.sharedVariable = this.sharedService.getSharedVariable();
}
}
通过以上步骤,你可以在ComponentA中更改共享变量的值,并在ComponentB中获取到更新后的值。这样,你就实现了从另一个同级组件中更改变量的功能。
关于Angular的更多信息和详细介绍,你可以参考腾讯云的Angular产品文档: Angular产品介绍
领取专属 10元无门槛券
手把手带您无忧上云