输入示例

@input 可用于在组件之间绑定数据

首先,将其导入组件中

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

然后,将输入添加为组件类的属性

@Input() car: any;

假设你的组件的选择器是’car-component’,当你调用组件时,添加属性’car'

<car-component [car]="car"></car-component>

现在你的汽车可以作为对象中的属性访问(this.car)

完整示例:

  1. car.entity.ts
    export class CarEntity {
       constructor(public brand : string, public color : string) {
       }  
    }
  1. car.component.ts
    import { Component, Input } from '@angular/core';
    import {CarEntity} from "./car.entity";
    
    @Component({
        selector: 'car-component',
        template: require('./templates/car.html'),
    })
    
    export class CarComponent {
        @Input() car: CarEntity;
    
        constructor() {
            console.log('gros');
        }
    }
  1. garage.component.ts
    import { Component } from '@angular/core';
    import {CarEntity} from "./car.entity";
    import {CarComponent} from "./car.component";
    
    @Component({
        selector: 'garage',
        template: require('./templates/garage.html'),
        directives: [CarComponent]
    })
    
    export class GarageComponent {
        public cars : Array<CarEntity>;
    
        constructor() {
            var carOne : CarEntity = new CarEntity('renault', 'blue');
            var carTwo : CarEntity = new CarEntity('fiat', 'green');
            var carThree : CarEntity = new CarEntity('citroen', 'yellow');
            this.cars = [carOne, carTwo, carThree];
        }
    }
  1. garage.html
    <div *ngFor="let car of cars">
    <car-component [car]="car"></car-component>
    </div>
  1. car.html
    <div>
        <span>{{ car.brand }}</span> |
        <span>{{ car.color }}</span>
    </div>