1

I'd like to conditionally display a child component (including its ContentChildren) within a parent component's template.

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>

desired result

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

Attempt for 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>
7
  • @Vega Yes, exactly Commented Aug 24, 2017 at 16:24
  • and you don't want to use ngif or ngswitch.. ? Commented Aug 24, 2017 at 16:25
  • @Vega It works witch ngIf, but the child component's <ng-content> is lost Commented Aug 24, 2017 at 16:26
  • @Vega What do you mean exactly? Commented Aug 24, 2017 at 16:31
  • @Vega I've tried so, but as the ContentChildren of child are defined outside of the parent component, they must remain dynamic. I've added my attempt with a wrapper in the question Commented Aug 24, 2017 at 16:40

1 Answer 1

1

You can do by usingngSwitch.

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

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

If you don't want the ngSwitch and need to change the entire template dynamically, hope the following answer will be helpful Dynamic template URLs in Angular 2 Ask

Sign up to request clarification or add additional context in comments.

2 Comments

the problem with that is that <ng-content> of the child component is static now, but it must be dynamic.
@Michel Cool If you need to change dynamically , the linked answer may be useful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.