Я пытаюсь отсортировать данные при изменении выбора радио. Я пытаюсь вызвать таблицу ngOnChanges, когда радиосигнал был изменен для сохранения.
Репозиторий Stackblitz здесь
Ниже приводится мой радиокомпонент, который отслеживает model.sortBy
значение модели.
radio.component.html
<div class="radioButtons">
<div class="left">
<input type="radio" value="name" ngModel="{{model.sortBy}}" (change)="changeSortBy('name')">Sort by name
</div>
<div class="right">
<input type="radio" value="age" ngModel="{{model.sortBy}}" (change)="changeSortBy('age')">Sort by age
</div>
</div>
Здесь событие changeSortBy
срабатывает при изменении выбора радиостанции. Я хочу обновить записи таблицы сразу после этого, поэтому она выполняет сортировку на основе выбора.
radio.component.ts
import { Component, OnInit, OnChanges } from '@angular/core';
import { TableComponent } from '../table/table.component';
@Component({
selector: 'app-radio',
providers: [RadioComponent],
templateUrl: './radio.component.html',
styleUrls: ['./radio.component.css']
})
export class RadioComponent {
model;
constructor() {
this.model = {
sortBy: "name"
}
}
changeSortBy(val: string, table: TableComponent) {
this.model = {
sortBy: val
}
//table.ngOnChanges();
}
returnModelState() {
//retur model.sortBy value
return this.model.sortBy;
}
}
Ниже приведен компонент таблицы, где данныебудет отображаться в отсортированном виде.
table.component.html
<div class="table-div">
<table class="table table-striped table-bordered table-hover full-width">
<tr>
<th class="course-name">Person Name</th>
<th class="duration">Date of Birth</th>
</tr>
<tr *ngFor="let b of birthdays">
<td style="height:50px;" class="course-name">{{b.name}}</td>
<td style="height:50px;" class="duration">{{b.birth}}</td>
</tr>
</table>
</div>
table.component.ts
import { Component, OnInit, Input, OnChanges, SimpleChanges } from '@angular/core';
import { RadioComponent } from '../radio/radio.component';
@Component({
selector: 'app-table',
providers: [RadioComponent],
templateUrl: './table.component.html',
styleUrls: ['./table.component.css']
})
export class TableComponent implements OnChanges {
birthdays = [
{
name: "User Sinha",
birth: "12/30/2011"
}, {
name: "Tom Cruize",
birth: "09/25/1992"
}, {
name: "Peter Jones",
birth: "01/24/1992"
}, {
name: "Ammy Trigger",
birth: "12/12/2001"
}
];
// this takes input from the radio component
sortBy: string;
constructor(private radio: RadioComponent) {
this.sortBy = radio.returnModelState();
}
ngOnChanges(changes: SimpleChanges) {
alert("ngOnChanges: " + this.sortBy);
this.sortItems();
}
sortItems() { }
}
Я пытаюсь разобраться с 2 днями, все еще не могу найти правильное решение.
Заранее спасибо!