在Angular中,数据绑定是一种将组件类中的数据与模板中的元素进行关联的机制。通过数据绑定,当组件类中的数据发生改变时,模板中的元素也会随之更新。
Angular提供了三种主要的数据绑定方式:插值表达式、属性绑定和事件绑定。下面是这些数据绑定方式的代码示例:
组件类中的代码:
export class AppComponent {
name = 'John Doe';
}
模板中的代码:
Welcome, {{ name }}!
组件类中的代码:
export class AppComponent {
imageUrl = 'https://example.com/image.jpg';
}
模板中的代码:
组件类中的代码:
export class AppComponent {
handleClick() {
console.log('Button clicked!');
}
}
模板中的代码:
这些是Angular中常用的数据绑定方式。通过这些数据绑定方式,可以实现组件类与模板之间的数据交互和事件响应。