Подтвердить что ты не робот

Передать переменную в пользовательский компонент

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

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

И использовать это в моем коде компонента?

4b9b3361

Ответ 1

Вам нужно добавить свойство 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>

Для получения дополнительной информации ознакомьтесь с этой страницей.

Ответ 2

Вы можете добавить декоратор @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() по @Input().