在Angular 9中,可以通过使用父组件中的复选框来选中/取消选中子组件中的复选框。下面是一种实现方法:
parentCheckboxValue
。<input type="checkbox" [(ngModel)]="parentCheckboxValue"> 父复选框
childCheckboxValue
。<input type="checkbox" [(ngModel)]="childCheckboxValue"> 子复选框
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-child-component',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnChanges {
@Input() parentCheckboxValue: boolean;
childCheckboxValue: boolean;
ngOnChanges(changes: SimpleChanges) {
if (changes.parentCheckboxValue) {
this.childCheckboxValue = this.parentCheckboxValue;
}
}
}
在上述代码中,通过使用@Input()
装饰器将父组件中的parentCheckboxValue
属性作为输入属性传递给子组件。然后,在ngOnChanges
生命周期钩子中,监听parentCheckboxValue
属性的变化,并将其值赋给子组件中的childCheckboxValue
属性。
这样,当父组件中的复选框状态改变时,子组件中的复选框状态也会相应地改变。
这种方法可以实现父子组件之间的复选框联动效果。在实际应用中,可以根据具体需求进行适当的修改和扩展。
推荐的腾讯云相关产品:腾讯云云服务器(CVM)和腾讯云云数据库MySQL。
领取专属 10元无门槛券
手把手带您无忧上云