ヘッダー、フッター、サイドバーなどを読み込む MasterComponent があります。ヘッダーには、ユーザーがログインするとオプションが設定されるドロップダウンがあります。異なる子コンポーネントを読み込む異なるルートに移動しても、ヘッダーは一定にしておきたいです。つまり、選択したオプションは変更されず、ドロップダウンの値はすべての子コンポーネントでアクセス可能でなければなりません。ドロップダウンの値が変更されると、現在の子コンポーネントが更新/再読み込みされる必要があります。
この問題にはどのように対処すればよいでしょうか? イベント リスナーのような機能が必要です。MasterComponent のモデルが変更されると、現在の子コンポーネントがリロードされます。MasterComponent の変数が更新されると、ChildComponent は更新をリッスンし、何らかの関数を実行するか、何らかの API を再度呼び出して、ChildComponent をリロードします。
// routes
const appRoutes: Routes = [
{
path: '',
redirectTo: 'login',
pathMatch: 'full',
},
{ path: 'login', component: LoginComponent },
{ path: 'logout', component: LogoutComponent },
{
path: '',
component: MasterComponent,
canActivate: [AuthGuard],
children: [
{ path: 'record/create', component: RecordCreateComponent }, // create record for selectedRestaurant in MasterComponent
{ path: 'record/', component: RecordComponent }, // shows all record of current selectedRestaurant in MasterComponent
{ path: 'record/:id/update', component:RecordUpdateComponent }, // show form to edit record having id
{ path: 'record/:id', component: RecordComponent }, // show record details having id
]
},
{ path: '**', redirectTo: 'login' }
];
// MasterComponent
@Component({
selector: 'master',
templateUrl: templateUrl,
styleUrls:[styleUrl1]
})
export class MasterComponent implements AfterViewInit, OnInit{
restaurants: Array<Restaurant> = [];
user:User;
selectedRestaurant: Restaurant;
constructor(private router: Router, private storageHelper:StorageHelper){
}
ngAfterViewInit() {
}
ngOnInit(){
this.user = JSON.parse(this.storageHelper.getItem('user'));
this.restaurants = this.user.restaurants;
this.selectedRestaurant = this.restaurants[0];
this.router.navigate(['/record/' + this.selectedRestaurant.id]);
}
onRestaurantChange(){
this.router.navigate(['/record/' + this.selectedRestaurant.id]);
}
createRecord(){
}
}
ベストアンサー1
@Input
子コンポーネントにデータを渡すには、ngOnChanges
(https://angular.io/api/core/OnChanges) を実行して、その@Input
場で変更されたかどうかを確認します。