代码之家  ›  专栏  ›  技术社区  ›  gonzo

将父级中定义的html传递给子级

  •  6
  • gonzo  · 技术社区  · 8 年前

    我试图在父组件中定义一些可以传递给子组件的html。这可能吗?我试过这样的方法: How to pass an expression to a component as an input in Angular2? ,但我没有任何运气。也许我的语法错了。我对 let . 感谢所有帮助和解释,以帮助我更好地理解这一点。

    @Component({
        selector: 'app-my-parent',
        template: `
        <div>other parent html</div>
        <app-my-child [property]="value">
            <ng-template #someTemplate">value.first</ng-template>
        </app-my-child>
        <app-my-child [property]="value">
            <ng-template #someTemplate">value.second</ng-template>
        </app-my-child>
        `
    })
    export class MyParent {
    }
    
    @Component({
        selector: 'app-my-child',
        template: `
        <div>other child html</div>
        how do I access the template from here? Is there a way to do binding with templates? 
    
    })
    export class MyChild {
          @Input() property;
    }
    
    2 回复  |  直到 8 年前
        1
  •  13
  •   bryan60    8 年前

    您需要向子组件添加一个ng内容标记,以便angular知道它应该屏蔽内容以及将内容放在哪里:

    @Component({
        selector: 'app-my-child',
        template: `
        <div>other child html</div>
        <ng-content></ng-content>
        `
    })
    export class MyChild {
    }
    

    然后需要删除ng模板标记,因为这告诉angular实际上根本不渲染这些东西,因为它们是要在其他地方使用的模板

    在父级中使用它非常简单:

    <app-my-child>Anything put between these component tags will be transcluded to the ng-content tag</app-my-child>
    
        2
  •  5
  •   BeetleJuice    8 年前

    正如@bryan60所指出的,子模板需要一个 <ng-content> . 在父选择器中,您放置在子选择器中的所有内容都将显示在ng内容位置,就在 AfterContentInit() 生命周期挂钩执行:

    父组件模板:

    <child-cmp>
      <p>This will appear within ng-content of ChildComponent</p>
    </child-cmp>
    

    子组件模板:

      <h2>I am ChildComponent</h2>
      <ng-content></ng-content>
    

    Live demo

    推荐文章