我的要求是有形式樹。在父窗體上點擊按鈕只會創建子窗體。它可以繼續這樣的n級。Angular 4:如何使用同一個組件作爲父母和孩子?
我的方法:
我已經創建了一個組件。這用作父母和孩子。點擊按鈕,我動態地將項目添加到ActivatedRoute的route.routeConfig.children。然後導航到相對於當前路徑的添加路徑。直到這一部分一切順利。 所以我在scren中看到所有的形式。我只想在屏幕上顯示活動窗體。然後點擊一個按鈕(後退按鈕),我想轉到它的父母並僅顯示該表單。在模板中使用* ngif打開子窗體時,我可以隱藏父窗體。但是回到孩子身後卻無法看清楚。以下是我的代碼。請讓我知道,如果有其他方法,我應該採取什麼額外的我需要添加,使其按我的方式工作。
我的組件。
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css'],
providers: [ConfigService]
})
export class TestComponent implements OnInit, OnDestroy {
name: string;
age: Number;
showParent: boolean = true;
childrenRoute: Routes;
message: any;
subscription: Subscription;
private sub: any;
constructor(private router: Router, private route: ActivatedRoute, private _configService: ConfigService) {
this.name = 'test data';
this.age = 20;
this.router = router;
if(this._configService.getConfig('showParent') != null){
this.showParent=false;
}
this.subscription = router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
if (_configService.getConfig('showParent') != null) {
this.showParent = _configService.getConfig('showParent');
}
}
});
}
ngOnInit() {
}
ngOnDestroy() {
// unsubscribe to ensure no memory leaks
this.subscription.unsubscribe();
}
showChildRecord() {
this.childrenRoute = [{
path: 'child',
component: TestComponent
}];
if (this.route.routeConfig != undefined) {
this.route.routeConfig.children = this.childrenRoute;
}
this._configService.setOption('showParent', false);
this.router.navigate(['./child'], { relativeTo: this.route });
}
back() {
this._configService.setOption('showParent', true);
this.router.navigate(["../"], { relativeTo: this.route });
}
}
我試過使用服務來共享相同組件的每個實例之間的數據。
@Injectable()
export class ConfigService {
private config = {};
setOption(option, value) {
this.config[option] = value;
}
getConfig(option: string) {
if(option != undefined){
return this.config[option] != undefined ? this.config[option]: null;
}else
return null;
}
}
模板test.component.html
<div *ngIf="showParent">
<p>Name:
<input type="text" [(ngModel)]="name">
</p>
<p>Age:
<input type="text" [(ngModel)]="age">
</p>
{{name}} : {{age}}
<button (click)="showChildRecord();" > Go to Child Record</button>
<button (click)="back();">Back</button>
</div>
<router-outlet></router-outlet>
App.module.ts路線:
const appRoutes: Routes = [
{
path: 'child',
component: TestComponent,
children: [
{ path: 'child',
component: TestComponent
}
]
}
];
我試圖存儲在服務和撥動 「showParent」 信息它取決於行動。在路由事件「NavigationEnd」下,我正在讀取它,並將它分配給showParent propery.But但它不起作用。我的父母表單仍然隱藏我只是看到空白的屏幕。我注意到的一個問題是「NavigationEnd」事件被多次觸發,可能是因爲我使用相同的組件,並且當創建新的子組件時,它會添加另一個事件。