私は、ヘッダー、フッター、サイドバーなどを読み込むMasterComponentを持っています。ヘッダーには、ユーザーがログインするとオプションが設定されるドロップダウンがあります。ロードする別のルートに移動しても、異なる子コンポーネント。選択されたオプションが変更されるべきではなく、ドロップダウンの値がすべての子コンポーネントでアクセス可能であることを意味します。ドロップダウン値の変更により、現在の子コンポーネントが更新/再ロードされる必要があります。親コンポーネントの変数が変更されたときに子コンポーネントを再ロードします。 Angular2
どのようにこの問題にアプローチする必要がありますか?私は、イベントリスナのような機能をしたい。 MasterComponent Changesのモデルを作成したら、現在の子コンポーネントを再ロードします。 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(){
}
}
質問のトピックは、「親コンポーネントを再読み込みせずに子コンポーネントを変更する」という誤解を招くトピックです。ルータを正しく設定するだけです。それは親ではないようです<->子供の問題。 – jmachnik
@jmachnik子コンポーネントから親変数にアクセスしたいのですが、その逆もあります。親コンポーネントの値は、すべてのルートで一貫している必要があります。 – Kaushal