Tìm kiếm trang web

angular - Truyền biến vào thành phần tùy chỉnh


Tôi có thành phần tùy chỉnh của mình:

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

Tôi có thể sử dụng nó như thế này:

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

Nhưng làm thế nào tôi có thể truyền một biến? Ví dụ:

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

Và sử dụng điều này trong mã thành phần của tôi?

Câu trả lời #1

Bạn cần thêm thuộc tính Input vào thành phần của bạn và sau đó sử dụng ràng buộc thuộc tính để truyền giá trị cho nó:

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);
    }
}

Và trong mẫu của bạn:

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

Để biết thêm thông tin, hãy xem trang này.

Câu trả lời #2

Bạn có thể thêm một decorator @Input() vào một thuộc tính trên component của bạn.

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

    @Input() title: string;
}


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

hoặc tiêu đề liên kết từ một biến 'theTitle'

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

Xem tài liệu về @Input()decorator.

Bài viết liên quan