Angular5将子组件中的HTML内容注入另一个组件

时间:2018-04-24 06:49:25

标签: html angular typescript angular-components

不确定这是否可行,但我有一个可重用的标题部分,它从路由数据属性中获取数据。这会在标题内显示标题和说明。

我的问题是,根据我所处的路线,如何将不同的HTML内容注入标题?我知道您可以使用ng-content,但这需要将标题部分放在每个组件中。标头位于主路由器插座外部

这是标题相对于路由器插座的定位

<app-navbar></app-navbar>
<app-header></app-header>
<app-alert></app-alert>
<router-outlet #route="outlet"></router-outlet>

这是标题

<div class="title">
  <div class="title-text">
    <h1>{{ data?.title }}</h1>
    <p>{{ data?.description }}</p>
  </div>
  <ng-content>Here is where I would like to inject HTML from child component</ng-content
</div>

这就是我想要注入的内容

  <label class="select" for="product-selection">Products</label>
  <select class="select" id="product-selection" placeholder="Product" [(ngModel)]="selectedProduct" (change)="onProductChanged()">
    <option *ngFor="let product of products" [value]="product.id">{{ product.name }}</option>
  </select>

1 个答案:

答案 0 :(得分:0)

如果标题位于主路由器插座之外,则必须使用在服务中创建全局变量,并使用* ngIF指令可以显示所需的标题。

实施此步骤的步骤: 1)从路由器获取值并保存在服务全局变量中。 2)在标题组件中使用该变量和* ngIf并显示标题值。

相关问题