gpt4 book ai didi

angular - 如何在组件之间共享 HTML?

转载 作者:行者123 更新时间:2023-12-05 02:18:31 27 4
gpt4 key购买 nike

我想在我的一些但不是全部组件之间共享一些 HTML(布局)。

app.compomonent.html:

<div class="classA">
<router-outlet></router-outlet>
</div>

我的一些组件(但不是全部)共享一些 HTML:

组件 X

<div class="classB">
<h2>{{Subtitle}}</h2>
</div>
<div class="classC">
X_SPECIFIC_HTML
</div>

分量 Y

<div class="classB">
<h2>{{Subtitle}}</h2>
</div>
<div class="classC">
Y_SPECIFIC_HTML
</div>

我想用实际组件 HTML 的占位符定义共享 HTML(注意数据绑定(bind)):

<div class="classB">
<h2>{{Subtitle}}</h2>
</div>
<div class="classC">
INSERT_COMPONENT_HTML_HERE
</div>

所以我的组件可以这样定义:

组件 X

X_SPECIFIC_HTML

分量 Y

Y_SPECIFIC_HTML

当前路线:

const appRoutes: Routes = [
{ path: 'x', component: XComponent },
{ path: 'y', component: YComponent }
];

这可能吗?

最佳答案

在其他地方获得帮助...

使用“内容投影”共享 HTML 非常容易。

数据绑定(bind)有点棘手,我设法使用 BehaviorSubject 做到了。

page-layout.component(共享的 HTML)

<div style="background-color: red;">
<h2>subtitle: {{subtitle}}</h2>
<ng-content></ng-content>
</div>
import { Component, OnInit } from '@angular/core';
import { LayoutService } from '../../services/layout.service';

@Component({
selector: 'page-layout',
templateUrl: './page-layout.component.html',
styleUrls: ['./page-layout.component.css']
})
export class PageLayoutComponent implements OnInit {

subtitle = '';

constructor(private LayoutService: LayoutService) {
}

ngOnInit() {
this.LayoutService.observable.subscribe(x => {
if (console) {
console.log('PageLayoutComponent, subscribe: ' + JSON.stringify(x));
}
this.subtitle = x.subtitle;
});
}
}

assembly-list.component(使用共享 HTML 的组件)

<page-layout>
<p>ToDo</p>
</page-layout>
import { Component, OnInit } from '@angular/core';
import { LayoutService } from '../../services/layout.service';

@Component({
selector: 'assembly-list',
templateUrl: './assembly-list.component.html',
styleUrls: ['./assembly-list.component.css']
})
export class AssemblyListComponent implements OnInit {

constructor(private LayoutService: LayoutService) {
}

ngOnInit() {
this.LayoutService.emitTitle(
'AssemblyListComponent1', 'AssemblyListComponent2'
);
}
}

布局服务(共享 HTML 的数据绑定(bind))

import { Component, Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

export interface ILayoutServiceData {
title: string;
subtitle: string;
}

@Injectable()
export class LayoutService {

private behaviorSubject: BehaviorSubject<ILayoutServiceData> =
new BehaviorSubject({title: null, subtitle: null});

observable = this.behaviorSubject.asObservable();

emitTitle(title: string, subtitle: string) {
if (console) {
console.log(`LayoutService.emitTitle(\'${title}\', \'${subtitle}\'`);
}
const data: ILayoutServiceData = {
title: title,
subtitle: subtitle
};
this.behaviorSubject.next(data);
}
}

关于angular - 如何在组件之间共享 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45184995/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com