首页 > 解决方案 > 将数据传递给与属性选择器一起使用的子组件

问题描述

我正在尝试使用带有属性类型选择器的子组件。我们如何将数据传递给这样的组件

我的子组件选择器看起来像

selector: '[hello]'

并且父组件模板写为

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

客户是一个对象

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

当我尝试使用属性绑定作为

[hello]="client"

或使用插值语法作为

hello="{{client}}"

我收到一个错误

无法绑定到“你好”,因为它不是已知属性

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

PS:我确实尝试过谷歌,但我得到的只是使用组件选择器作为元素

标签: angular

解决方案


一种方法是创建一个Input()与属性选择器同名的属性hello。没有任何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;
}

母公司

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

分叉演示


推荐阅读