Angular: How to capture checkbox change event and update content in a non-parent component

血红的双手。 提交于 2021-01-28 00:32:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!