将变量传递给自定义组件

时间:2017-02-17 00:30:27

标签: angular angular2-template angular2-components

我有自定义组件:

@Component({
    selector: 'my-custom-component',
    templateUrl: './my-custom-component.html',
    styleUrls: ['./my-custom-component.css']
})
export class MyCustomComponent {
    constructor() {
        console.log('myCustomComponent');
    }
}

我可以这样使用它:

<my-custom-component></my-custom-component>

但我如何传递变量呢?例如:

<my-custom-component custom-title="My Title"></my-custom-component>

并在我的组件代码中使用它?

2 个答案:

答案 0 :(得分:37)

您需要将Input属性添加到组件中,然后使用属性绑定将值传递给它:

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

@Component({
    selector: 'my-custom-component',
    templateUrl: './my-custom-component.html',
    styleUrls: ['./my-custom-component.css']
})
export class MyCustomComponent {

    @Input()
    customTitle: string;

    constructor() {
        console.log('myCustomComponent');
    }

    ngOnInit() {
        console.log(this.customTitle);
    }
}

在你的模板中:

<my-custom-component [customTitle]="yourVariable"></my-custom-component>

有关详细信息,请查看this page

答案 1 :(得分:8)

您可以将@Input()装饰器添加到组件的属性中。

export class MyCustomComponent {
    constructor() {
        console.log('myCustomComponent');
    }

    @Input() title: string;
}


<my-custom-component title="My Title"></my-custom-component>

或来自变量'theTitle'的绑定标题

<my-custom-component [title]="theTitle"></my-custom-component>

请参阅@Input()decorator文档。