2017-02-17 22 views
2

我有我的自定義組件:傳遞變量來定製組件

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

並在我的組件代碼中使用它?

+0

在組件中使用輸入:https://angular.io/docs/ts/latest/guide/template-syntax.html#!#inputs-outputs –

回答

7

您需要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

+2

這項工作!任何想法爲什麼'customTitle'變量在'constructor()'中是未定義的? – rpayanm

+2

@rpayanm它是'undefined',因爲'Input'是Angular的裝飾器,dit通過Angular的生命週期「生活」,因此它只能在'OnInit'中使用,並且('constructor'與Angular沒有任何關係,所以它被初始化在'OnInit'之前)。你可以在這裏閱讀更多關於Angular的生命週期鉤子:https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html –

+0

但是如何訪問字符串「myAnotherVariable」? myAnotherVariable

3

您可以將@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文檔。