輸入示例

@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>