2017-02-17 7 views
2

У меня есть пользовательский компонент:Pass переменной пользовательского компонента

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