将变量传递给自定义组件

我有我的自定义组件:

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

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

127254 次浏览

You can add an @Input() decorator to a property on your component.

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


@Input() title: string;
}




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

or binding title from a variable 'theTitle'

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

See the @Input()decorator documentation.

You need to add Input property to your component and then use property binding to pass value to it:

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

And in your template:

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

For more info, check out this page.