Angular 组件在侦测到其输入属性或数据绑定发生更改时,会重新渲染该组件。以下是 Angular 中如何处理数据更新并重新渲染组件的示例代码。
假设有一个简单的组件,其中包含一个输入属性 title:
@Component({ selector: 'app-my-component', template: '
在另一个组件或服务中,可以更改该属性的值并观察 MyComponent 是否重新渲染。这可以通过使用组件的引用并更改其值来完成:
export class MyOtherComponent { @ViewChild(MyComponent) myComponent: MyComponent;
updateTitle() { this.myComponent.title = 'New Title'; } }
在 updateTitle() 方法中更改 title 属性的值会触发 MyComponent 的重新渲染。
注意:当属性作为基本类型(例如字符串或数字)绑定到组件时,更改该属性的值不会被检测到。如果需要在更改属性时重新渲染组件,请使用可变对象或数组来绑定属性(例如 NgModel)。
这是使用 NgModel 将属性绑定到输入框,以便可以监视更改并重新渲染组件的示例代码:
@Component({ selector: 'app-my-component', template: '
现在,任何更改输入框中的值都将更新组件的 title 属性,并触发组件的重新渲染。