【问题标题】:Conditionally display child component and its content within parent component有条件地在父组件中显示子组件及其内容
【发布时间】:2017-08-24 16:08:45
【问题描述】:

我想有条件地在父组件的模板中显示一个子组件(包括它的 ContentChildren)。

app.component.html

<parent>
  <child #initial>
    <span>Player</span>
  </child>
  <child label="Intro">
    <span>Intro</span>
  </child>
  <child label="Content">
    <span>Content</span>
  </child>
</tabs>

想要的结果

<parent>
  <child>
    <span>Player</span>
  </child>
</parent>

parent.component.ts

@Component({
  selector: 'parent',
  template: `<!--Display {{current}} and its ContentChildren-->`,
  styleUrls: ['./tabs.component.scss']
})

export class ParentComponent implements OnInit {
  @ContentChildren(ChildComponent) childs;
  @ContentChild("initial") initial;
  @ContentChild("open") current;
  ngOnInit(): void {
    if (this.initial) this.current = this.initial;
  }
}

child.component.ts

@Component({
  selector: 'child',
  template: `<ng-content></ng-content>`,
})

export class ChildComponent {
  @Input() label: string;
}

尝试 parent.component.html

<ng-container *ngFor="let child in childs">
  <child *ngIf="child == current"></child> //ContentChildren as defined in 'app.component.html' are lost now 
</ng-container>

【问题讨论】:

  • @Vega 是的,完全正确
  • 你不想使用 ngif 或 ngswitch.. ?
  • @Vega 它可以在 ngIf 中工作,但是子组件的 丢失了
  • @Vega 你到底是什么意思?
  • @Vega 我已经尝试过了,但是由于子组件的 ContentChildren 是在父组件之外定义的,因此它们必须保持动态。我在问题中添加了包装器的尝试

标签: angular typescript


【解决方案1】:

您可以使用ngSwitch

<parent>
  <div [ngSwitch]="current">
      <child1 *ngSwitchCase="'Intro'" label="Intro">
          <span>Intro</span>
      </child1>

      <child2 *ngSwitchCase="'Content'" label="Content">
          <span>Content</span>
      </child2>
  </div>
</parent>

如果你不想要ngSwitch 并且需要动态更改整个模板,希望以下答案会有所帮助 Dynamic template URLs in Angular 2 Ask

【讨论】:

  • 问题在于子组件的现在是静态的,但它必须是动态的。
  • @Michel Cool 如果您需要动态更改,链接的答案可能有用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-16
  • 2011-07-11
  • 2015-03-19
  • 2020-09-03
相关资源
最近更新 更多