我有一个“设置”组件,该组件将用于更改另一个组件的文本和背景颜色,但是我不确定最好的解决方法。
如果它们包含在同一组件中,我知道如何更改文本和背景的样式,我只是不确定不同组件之间的通信方式。
我有一个stackblitz及其示例代码
app.component.html
<settings></settings>
<my-comp></my-comp>
my-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
}
}
此后,我一直试图使一项服务正常工作,但似乎进展不顺利。
service.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');
}
我的电脑-订阅颜色更改
@ViewChild('textDiv')
private text: ElementRef;
constructor(private service: SettingsService) {
this.service.getColour.subscribe(res => {
this.text.nativeElement.style.background = res;
});
}
答案 0 :(得分:3)
答案 1 :(得分:2)
创建一个服务以在组件之间进行通信。您要做的就是在服务中创建一个可观察对象,然后可以在一个组件中发出更改,并订阅另一个组件中的更改。有角度的文档在这里https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service对此进行了解释。
基于更新
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');
}
我的计算机
@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();
}