Component child selector with extended template

124 Views Asked by At

I want to create component with view hierarchy outside of Router and RouterModule

Example:

comp-parent.ts

@Component({
  selector: 'comp-parent',
  template: `
        <p>parent works</p>
        <router-outlet></router-outlet>
        `,
  styleUrls: ['./comp-parent.css']
  })
export class ComponentParent { 
    protected foo: string;
}

comp-children.ts

@Component({
  selector: 'comp-children',
  template: "<p>Children works</p>",
  styleUrls: ['./comp-children.css']
  })
export class ComponentChildren extends ComponentParent { }

component-foo-bar.ts

@Component({
  selector: 'component-foo-bar',
  template: "<comp-children></comp-children>",
  styleUrls: ['./component-bar.css']
  })
export class ComponentFooBar { }

In ComponentBar I would expect that comp-children will be comp-parent with comp-children included, but only comp-children template is loaded.

How to load parent template with <router-outlet/> resolved to comp-children template?

3

There are 3 best solutions below

0
Baruch Gans On

Just replace the

@Component({
  selector: 'component-foo-bar',
  template: "<comp-children>",
  styleUrls: ['./component-bar.css']
  })
export class ComponentFooBar { }

with

@Component({
  selector: 'component-foo-bar',
  template: "<comp-children></comp-children>",
  styleUrls: ['./component-bar.css']
  })
export class ComponentFooBar { }
2
dileepkumar jami On

When you inherit a class, only you can use the logic of the base class but not the template of it.

Infact, you have not used the child component inside the parent component. ( I meant using child component selector in parent component template)

So they are not parent and child actually and they are just base and derived classes

1
Bardr On

If you want to make such hierarchy you don't need to use router-outlet nor inheritance. Just use components directly (by selectors). See StackBlitz demo.