如何在Angular 2组件之间共享HTML

时间:2017-07-19 08:28:02

标签: angular

我是Angular的新手并且遇到了问题。

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

app.compomonent:

<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(注意数据绑定):

<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 }
];

这可能吗?

1 个答案:

答案 0 :(得分:3)

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

使用“内容投影”分享HTML非常简单。

数据绑定有点棘手,我设法使用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的数据绑定)

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);
  }
}