【问题标题】:Angular 2 component - multiple occurrences with the same selectorAngular 2 组件 - 使用相同的选择器多次出现
【发布时间】:2018-07-18 13:38:24
【问题描述】:

我得到了一个具有以下定义的组件类:

@component({
    selector: 'app-table',
    template: '<div #content></div>',
    styleUrls: ['./table.component.css']
});

export class TableComponent implements OnInit{
    @ViewChild('content') elm: ElementRef;
    ....
}

但是,在父 html 中,结构是:

<div label="summary1">
   <app-table type="thisMonth"></app-table>
</div>
<div label="summary2">
   <app-table type="lastMonth"></app-table>
</div>

我的问题是,我怎样才能将生成不同的内容并放入相应的'app-table'?

我尝试使用以下方法,它返回未定义:

export class TableComponent implements OnInit{
    @ViewChildren('content') elms: <QueryList>ElementRef;

谢谢!

【问题讨论】:

  • 使用 @Input() 装饰器从父组件接收数据,即在您的情况下为“类型”。
  • @AkshayRana 感谢您的回复。所以我需要做的是声明:@Input() type: string;在父组件中,并在父组件中新建2个TableaComponent对象来生成对应的内容,对吗?
  • 不,你必须声明@Input() type: string;在子组件(即 TableComponent)中,这意味着它需要一个名为“type”的输入,现在无论您想渲染这个组件,您都可以动态发送类型,就像您已经在这里所做的那样:。因此,在这种情况下,您将获得“thisMonth”作为为上述标签呈现的 Table 组件中的类型值。之后,您可以在 Table 组件中构建您的逻辑。

标签: angular typescript


【解决方案1】:

正如@Akshay Rana 在他的 cmets 中提到你必须使用 @Input 装饰器来传递数据,他是绝对正确的。 我正在更详细地扩展他的答案。正如您所要求的,您需要生成不同的内容并放入相应的“应用程序表”中,如果内容是 HTML,那么只有 @Input 装饰器将不起作用。因此,我分享了一个 URL,您可以在其中找到所有答案,包括使用 @Input、@Output 装饰器等,如果您需要进一步说明,请查看并告诉我。 How to get inner html of Angular6 component and add it to component template?

【讨论】:

  • 非常感谢!我会参考你的网址再试一次!
猜你喜欢
  • 2016-08-03
  • 1970-01-01
  • 2013-01-30
  • 2017-01-24
  • 1970-01-01
  • 2017-04-25
  • 2017-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多