简体   繁体   中英

Get value of a variable in one component to another component using ngmodel

I have two components first and second . From the second component, I am calling the first component. In the first component, I have a matslider module and I want to get that slider on/off status to my second component ts file. So I am getting that value in first, but don't know how to pass that to the second component.

first.component.html

<div>
<mat-slide-toggle class="toggles" 
(change)="OnToggle($event) 
[(ngModel)]="selected">Toggle</mat-slide-toggle>
</div>

first.component.ts

@Input() selected=false;
public OnToggle(event)
{
  this.selected = event.selected;
}

second.component.html

<div class="container">
<app-first> </app-first>
</div>

I think you can use an output event in the first component and bind to it in the second component.

here it is example:

First Component:

  @Output() selectedChange = new EventEmitter<boolean>();

  public OnToggle(event) {
  this.selected = event.selected;
  this.selectedChange.emit(this.selected);

}

SecondComponent :

<app-first (selectedChange)="onSelectedChange($event)"></app-first>


public onSelectedChange(selected: boolean) {
  console.log(selected);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM