在Angular中,@Attribute装饰器用于将组件的属性绑定到构造函数中。以下是一个示例解决方案:
首先,创建一个名为MyComponent
的组件,并使用@Attribute装饰器将组件的属性绑定到构造函数中:
import { Component, Attribute } from '@angular/core';
@Component({
selector: 'my-component',
template: '{{title}}
'
})
export class MyComponent {
title: string;
constructor(@Attribute('title') title: string) {
this.title = title;
}
}
然后,在父组件的模板中使用
标签,并通过属性绑定传递一个值给title
属性:
当父组件加载时,它会在title
属性上设置值,并传递给MyComponent
的构造函数。MyComponent
将使用传递的值来设置title
属性,并将其显示在组件的模板中。
请注意,@Attribute装饰器只能用于构造函数参数,并且只能在组件的构造函数中使用。它不能用于其他方法或属性。
上一篇:Angular绑定到弹出窗口