htmlangularangular-materialangular-ngmodel

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>

Solution

  • 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);
    }