我目前正在构建一个包含多个dashlet组件的仪表板,这些组件都共享相同的输入。所有输入都在基本组件中定义。我想在仪表板组件中做的是使用ngFor动态创建所有小面板,并使用基本组件作为一种占位符,它将被子组件替换。
我正在寻找一个可以使用输入和输出装饰器的解决方案,因为它使代码更易于维护。它使整个故事与ChangeDetection更简单,我可以使用像ngOnChanges这样的东西。所以ComponentFactory不是我正在寻找的解决方案,尽管它在技术上有效。
这是我正在考虑的一个例子:
base.component.ts
@Component({
selector: 'app-base',
templateUrl: './base.component.html',
styleUrls: ['./base.component.scss']
})
export class BaseComponent implements OnInit {
@Input() id: number;
@Input() name: string;
constructor() { }
ngOnInit() { }
}
child.component.ts
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ChildComponent extends BaseComponent implements OnInit, OnChanges {
constructor() {
super();
}
ngOnInit() { }
ngOnChanges() {
// do something on changes
}
}
dashboard.component.html
<div *ngFor="let dashlet of dashletList">
<app-base [id]="dashlet.id" [name]="dashlet.name" *ngComponentOutlet="dashlet"></app-base>
<!-- later app-base withh be replaced by app-child or any other dashlet-->
</div>
你可以在BaseComponent中使用ng-content
,这样你就可以将所有常见的部分放在BaseComponent中,但是所有的部分都来自ng-content
下的子组件。在AppComponent中,相应地更改它,
<div *ngFor="let dashlet of dashletList">
<app-base [id]="dashlet.id" [name]="dashlet.name">
<ng-container *ngComponentOutlet="dashlet.type"></ng-container>
</app-base>
<!-- later app-base withh be replaced by app-child or any other dashlet-->
</div>
但是z zxswい