我有一个“设置”组件,用于更改另一个组件的文本和背景颜色,但是我不确定最好的方法。
如果文本和背景包含在同一个组件中,我知道如何更改它们的样式,我只是不确定不同组件之间的通信。
我的示例代码有一个stackblitz
应用程序组件.html
<settings></settings>
<my-comp></my-comp>
我的comp.component.html
<div #textDiv>
<p>This is the component where the text and background will change colour</p>
<p>Lorem ipsum dolor sit amet, consectetur adipis.</p>
</div>
settings.component.html
<div class="container" [ngClass]="{expanded: toggled}">
<a class="material-icons" (click)="toggle()">settings</a>
<div>
<button (click)="changeTextColour()">Change text</button>
<button (click)="changeBackgroundColour()">Change BG</button>
</div>
</div>
settings.component.ts
export class SettingsComponent {
toggled = false;
toggle() {
this.toggled = !this.toggled;
}
changeTextColour() {
// Do something
}
changeBackgroundColour() {
// Do something
}
}
从那以后,我试图让一项服务工作,但似乎进展不顺利。
服务.ts
export class SettingsService {
text = new Subject();
setColour(colour) {
this.text = colour;
}
get getColour(): Observable<any> {
return this.text;
}
}
settings.ts -从组件设置颜色
constructor(private settings: SettingsService) {}
changeTextColour() {
this.settings.setColour('green');
}
my-comp.ts -订阅颜色变化
@ViewChild('textDiv')
private text: ElementRef;
constructor(private service: SettingsService) {
this.service.getColour.subscribe(res => {
this.text.nativeElement.style.background = res;
});
}
创建服务以在组件之间进行通信。您所要做的就是在服务中创建一个 observable,然后您可以在一个组件中发出更改并订阅另一个组件中的更改。angular Docs 在这里解释了它https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service。
基于更新
服务.ts
export class SettingsService {
text = new Subject<string>();
colourChanged$ = this.text.asObservable();
setColour(newColour) {
this.text.next(newColour);
}
}
settings.component.ts
constructor(private settings: SettingsService) {}
changeColour() {
this.settings.setColour('green');
}
我的comp.ts
@ViewChild('textDiv') private text: ElementRef;
subscription: Subscription;
constructor(private settings: SettingsService) {
this.subscription = settings.colourChanged$.subscribe(
colour=> {
this.text.nativeElement.style.background = colour;
});
}
ngOnDestroy() {
// prevent memory leak when component destroyed
this.subscription.unsubscribe();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句