问题描述
我有一个带有复选框的组件.<mat-checkbox class="mr-5"></mat-checkbox>
勾选的时候需要捕获,然后根据checkbox的勾选在另一个组件中显示文本/选择.第二个组件不是具有复选框的组件的父级.
I have a component which has a checkbox. <mat-checkbox class="mr-5"></mat-checkbox>
I need to capture when it is checked, and then display text in another component based on the checkbox tick/selection. The second component is not the parent of the component which has the check box.
如何从非父组件捕获复选框值更改?我是 Angular 的新手.如果我能得到一个例子真的很感激.
How can I capture the checkbox value change, from the non-parent component? I am new to Angular. Really appreciate if I could get an example.
推荐答案
存在不同的方式来实现组件之间的传输事件.我认为最好创建服务:
Exists different ways for implement transfer events between components. I think that better create service:
//SERVICE
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ChangeService {
private checkEvent = new BehaviorSubject<boolean>(false);
check = this.checkEvent.asObservable();
constructor() {
}
onChangeCheck(data: boolean) {
this.checkEvent.next(data);
}
}
//COMPONENT WITH CHECKBOX
export class FirstComponent implements OnInit {
constructor(
private service: ChangeService
) { }
ngOnInit(): void {
}
onChange(event) {
this.service.onChangeCheck(event.checked);
}
}
//COMPONENT WITH TEXT
export class SecondComponent implements OnInit {
isVisibleText = false;
constructor(
private service: ChangeService
) { }
ngOnInit(): void {
this.service.check
.subscribe(checked => {
this.isVisibleText = checked;
});
}
}
这篇关于Angular:如何捕获复选框更改事件并更新非父组件中的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!