【问题标题】:Render Component On To another Component Angular 5将组件渲染到另一个组件Angular 5
【发布时间】:2018-08-13 15:36:07
【问题描述】:

我有一个我创建的组件及其称为选项,因为它呈现编辑和删除按钮。然后我有一个可重用的表格组件。我将表格组件注入到站点上的视图中。然后我导入选项组件,但我没有在该视图上显示它,因为我想将它传递给表格组件并将其呈现给标记。是否可以将选项组件从主组件传递到表组件并注入它,因为不是没有具有相同选项组件的表。

options.component.ts

@Component({
    selector: 'options',
    template: `
        <div class="btn-group btn-group-toggle" data-toggle="buttons">
            <label class="btn btn-secondary active">
                <input type="radio" name="options" id="option" autocomplete="off" checked>Edit
            </label>
            <label class="btn btn-danger">
                <input type="radio" name="options" id="option" autocomplete="off" checked>Delete
            </label>
         </div>`,
    styles: []
})

export class OptionsComponent implements OnInit {
     constructor() { }

     ngOnInit() { }
}

main.component.ts

import { TableComponent } 'file location here';
import { OptionsComponent } 'file location here'; // Component is injected here and I want to pass it to <app-table></app-table>
@Component({
    selector: 'app-main',
    template:'<app-table [tableData]="LocationsList"></app-table>'
})

export MainComponent implements OnInit {
    LocationsList: []; // list of locations

}

table.row.component.ts

@Component({
    selector: 'app-table',
    template: `
       <ul>
          <li *ngFor="let property of tableData">{{ property }}</li>
       </ul>`,
})

export class TableComponent implements OnInit {
     @Input() tableData: any[];
} 

【问题讨论】:

  • 请添加一些代码以更好地说明您当前的结构。
  • 我更新了@zz

标签: angular components angular-components


【解决方案1】:

如果您想将信息注入到子组件中,请像这样使用@input。

子组件.ts:

@Input() inputVariableName: InputObjectType;

父组件.html:

<app-child-selector [inputVariableName]="parentComponentVariableName">
</app-child-selector>

如果你想将信息从子组件传递到父组件,它有点复杂,但我建议使用观察者模式,带有服务和事件发射器。 希望对您有所帮助。

【讨论】:

    【解决方案2】:

    如果你想将 HTML 作为参数传递给组件,有很多方法,有好处也有局限性。 大部分不同:

    1. 内容投影。搜索&lt;ng-content&gt;。 (最简单但有很大的局限性)
    2. 将模板作为参数传递。搜索 @ContentChildrenTemplateRefViewContainerRef、结构指令。 (灵活)
    3. 将组件的类型传递为@Input 并将其呈现在另一个内部(使用ViewContainerRef.createComponent[ngComponentOutlet] 等)。 (看起来很脏)

    他们需要一些帮助代码。他们可能有一些“变态”。选择取决于许多原因。

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 2019-03-03
      • 1970-01-01
      • 2013-01-20
      • 2018-01-26
      • 2019-04-19
      • 1970-01-01
      • 2018-07-21
      • 2018-07-12
      相关资源
      最近更新 更多