Angular 2 输入例

示例

@input对于在组件之间绑定数据很有用

首先,将其导入您的组件中

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

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

@Input() car: any;

假设您组件的选择器是“ car-component”,当您调用该组件时,添加属性“ car”

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

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

完整示例:

  1. 实体

    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>