在Angular中,子组件不会自动检测父组件的更改。为了解决这个问题,我们可以使用@ Input装饰符来传递变量,并使用ngOnChanges ()钩子来手动检测变化。 示例代码如下:
// 父组件模板
// 子组件代码 import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnChanges { @Input() someInput: any;
ngOnChanges(changes: SimpleChanges) { if (changes.someInput) { // 处理输入变量更改的逻辑 //例如: console.log('Some input value changed'); } } }
在上面的示例中,当someInput变更时,ngOnChanges钩子将被调用,并且我们可以在其中处理输入变量更改的逻辑。