【问题标题】:Component child selector with extended template带有扩展模板的组件子选择器
【发布时间】:2019-07-08 14:25:13
【问题描述】:

我想在 Router 和 RouterModule 之外创建具有视图层次结构的组件

例子:

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

组件-foo-bar.ts

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

ComponentBar 中,我预计comp-children 将是comp-parent,其中包含comp-children,但仅加载了comp-children 模板。

如何加载&lt;router-outlet/&gt;解析为comp-children模板的父模板?

【问题讨论】:

  • 在您的 component-foo-bar.ts 文件中,您使用了 templateUrl,但直接给出了 html。是不是贴代码有误?
  • 是的,错字。固定。
  • “在路由器和路由器模块之外”并使用router-outlet 是什么意思?

标签: angular angular7 view-hierarchy


【解决方案1】:

只需更换

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

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

【讨论】:

    【解决方案2】:

    继承类时,只能使用基类的逻辑,不能使用基类的模板。

    其实你并没有在父组件里面使用子组件。 (我的意思是在父组件模板中使用子组件选择器)

    所以它们实际上不是父类和子类,它们只是基类和派生类

    【讨论】:

    • 如果您将整个代码发布在堆栈闪电战上会更好
    • 路由器和状态路由像我描述的那样工作,(如果你定义了正确的 RoutingModule),但我想在 URL 路由之外使用它。
    【解决方案3】:

    如果你想建立这样的层次结构,你不需要使用router-outlet 也不需要继承。只需直接使用组件(通过选择器)。请参阅StackBlitz 演示。

    【讨论】:

    • 它是更大机制的一部分,我不能像您的示例中提供的那样在父组件中使用子组件,因为它没有扩展基本模板。它只是在parent-component 中使用children-component
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    相关资源
    最近更新 更多