将变量传递给自定义组件 [英] Pass variable to custom component
本文介绍了将变量传递给自定义组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有我的自定义组件:
@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>
但是我如何传递一个变量呢?例如:
But how I can pass a variable? For example:
<my-custom-component custom-title="My Title"></my-custom-component>
并在我的组件代码中使用它?
And use this in my component code?
推荐答案
您需要将 Input
属性添加到您的组件中,然后使用属性绑定将值传递给它:
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);
}
}
在您的模板中:
<my-custom-component [customTitle]="yourVariable"></my-custom-component>
有关详细信息,请查看此页面.
For more info, check out this page.
这篇关于将变量传递给自定义组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文