我有 3 个组件“starter-left-side”、“starter-content”、“camera”。 1 服务“一般参数”。在 generalParameters 中,我有 2 个属性; 'contentHeader' 和 contentDescription 分别具有默认字符串值。
初始化 starter-content 后,我从 generalParameters 获取这些值并将其呈现在 starter-content.html 中。当我想转到 camera.component 时,我也只需通过 starter-left-side 单击指向 camera.component 的链接,我在 starter-left-side 中有一个方法可以设置 generalProperties 的属性值一旦链接被点击,它就可以被 starter-content 再次使用。
我可以成功更改 generalProperties 中的值,但问题是,它不再呈现在起始组件中。我不知道我应该在生命周期 Hook 的哪个时间再次从 generalProperties 获取值,以便它可以在 starter-content.html 中呈现。
generaParameters.service.ts
contentHeader: string;
contentDescription: string;
constructor() {
this.contentHeader = "Dashboard";
this.contentDescription = "This is your dashboard";
}
starter-content.component.html
<h1>
{{pageHeader}}
<small>{{description}}</small>
</h1>
starter-content.component.ts
pageHeader: string;
description: string;
constructor(
private gp: GeneralparametersService
) { }
ngOnInit() {
this.pageHeader = this.gp.contentHeader;
this.description = this.gp.contentDescription;
}
starter-left-side.component.ts
setContent(header, description) {
this.gp.contentHeader = header;
this.gp.contentDescription = description;
}
starter-left-side.component.html
<li class="active"><a href="avascript:void(0);" (click)="setContent('Camera', 'Using Camera')" [routerLink]="['camera']"><i class="fa fa-link"></i> <span>Camera</span></a></li>
非常感谢您的帮助。
最佳答案
由于您正在使用服务进行通信,因此您可以使用 Subject
当您通过 gp.setContent
更改您的主题时,因为您的其他组件正在观察更改,它们将自动更新。
我用了pluck这样我们就可以只取我们需要的属性,单独渲染。
查看我的实现。希望能帮助到你!!!
starter-left-side.component.html
<li class="active"><a href="javascript:void(0);" (click)="gp.setContent('Camera', 'Using Camera')" [routerLink]="['camera']"><i class="fa fa-link"></i> <span>Camera</span></a></li>
generaParameters.service.ts
import { Subject } from 'rxjs';
private mycontent$ = new Subject();
public content$ = this.mycontent$.asObservable();
setContent(header, description) {
this.content$.next({header, description});
}
starter-content.component.ts
import { pluck } from 'rxjs/operators';
ngOnInit(): void {
this.pageHeader$ = this.gp.content$.pipe(pluck('header'));
this.pageDescription$ = this.gp.content$.pipe(pluck('description'));
}
starter-content.component.html
<h1>
{{pageHeader$ | async }}
<small>{{pageDescription$ | async}}</small>
</h1>
关于javascript - 从另一个组件更改组件的属性并将其呈现在 angular 2 的 html 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51778580/