简体   繁体   English

将数据传递给与属性选择器一起使用的子组件

[英]Pass data to child component used with attribute selector

I am trying to use a child component with an attribute type selector.我正在尝试使用带有属性类型选择器的子组件。 How can we pass data to such component我们如何将数据传递给这样的组件

My child component selector looks like我的子组件选择器看起来像

selector: '[hello]'

and the parent component template is written as并且父组件模板写为

<ng-container *ngFor="let client of clients">
    <tr hello="client"></tr>
</ng-container>

where clients is an object as其中客户是 object 为

clients: any[] = [
    { firstName: 'Ajay', lastName: 'Kumat' },
    { firstName: 'Vijay', lastName: 'Kumar' }
]

when I try to use property binding as当我尝试使用属性绑定作为

[hello]="client"

or use interpolation syntax as或使用插值语法作为

hello="{{client}}"

I get an error as我收到一个错误

Can't bind to 'hello' since it isn't a known property无法绑定到“你好”,因为它不是已知属性

Stackblitz at https://stackblitz.com/edit/angular-attribute-selector-child-pass-data Stackblitz 在https://stackblitz.com/edit/angular-attribute-selector-child-pass-data

PS: I did try to google but all I get is using component selector as element PS:我确实尝试过谷歌,但我得到的只是使用组件选择器作为元素

One way is to create an Input() property with the same name as of the attribute selector hello .一种方法是创建一个与属性选择器hello同名的Input()属性。 Without any Input() property, you cannot pass any data to it.如果没有任何Input()属性,则无法将任何数据传递给它。

import { Component, Input } from '@angular/core';

@Component({
  selector: '[hello]',
  template: `<td>{{hello.firstName}}</td>
  <td>{{hello.lastName}}</td>`
})
export class HelloComponent  {
  @Input() hello: any;
}

parent comp母公司

<ng-container *ngFor="let client of clients">
    <tr [hello]="client"></tr>
</ng-container>

Forked demo分叉演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM