问题
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.
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.
回答1:
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;
});
}
}
回答2:
try this one,
in HTML
<mat-checkbox class="mr-5" (click)="onChecked($event)"></mat-checkbox>
in TS
onChecked(e){
if(e.target.checked){
// check box Checked
}else{
// check box unChecked
}
}
来源:https://stackoverflow.com/questions/64149570/angular-how-to-capture-checkbox-change-event-and-update-content-in-a-non-parent