使用组件继承时有什么特别的事吗?
编辑:这涉及INHERITANCE,而不是父/子视图/组件通信
当我试图隐藏在基类模板中定义的div时,它不起作用
在页面中,即使在代码中修改了变量,该变量也不会更新
1,我试过[hidden]和* ngIf
然后我尝试使用changeDetectorRef,但它没有做任何事情
似乎值不会传播到模板
基类:
@Component({
selector: 'my-content',
templateUrl: './content.component.html',
styleUrls: ['./content.component.css'],
})
export class ContentComponent implements OnInit {
protected overlayVisible:boolean;
constructor(....){...}
ngOnInit() {
}
showOverlay()
{
this.overlayVisible=true; <<<<<<<<<<<<<< THESE GET CALLED
}
hideOverlay()
{
this.overlayVisible=false; <<<<<<<<<<<<<< THESE GET CALLED
}
}
基本模板(content.component.html):
<div>
<div class="contentMainDiv">
<div class="contentBodyDiv"><ng-content select="[body]"></ng-content></div>
<div [innerHTML]=" overlayVisible?'true':'false' "></div> /// DEBUG DIV
<div [hidden]="!overlayVisible" class="contentOverlay" >
<my-wait></my-wait>
</div>
</div>
</div>
子组件:
export class CustomersComponent extends ContentComponent implements OnInit {
private customers: any;
constructor(
private customersService: CustomersService,
injector:Injector
) { super(injector); }
getCustomers() {
this.showOverlay();
this.customersService.getCustomers().subscribe((customers: any) => {
this.customers = customers;
this.hideOverlay();
});
}
儿童模板:
<my-content>
<div body>
<div *ngIf="customers">
some table ...
</div>
</div>
</my-content>
我错过了什么
当我们使用组件继承时,有什么特别的事吗?
谢谢
4 回答
你想调用一个位于父组件中的方法,对吧?那么
EventEmitter
可以帮到你:<child-component (showOverlay)="showOverlay()" (hideOverlay)="hideOverlay()"></child-component>
子组件:
我假设您销毁子组件然后想要隐藏叠加,因此在
ngOnDestroy
中发出hideOverlay
.子类中的变量不会受子类中的执行方法的影响 . 当你执行this.showOverlay()时,它在子组件的范围内修改了this.overlayVisible . 使用组件交互https://angular.io/guide/component-interaction#parent-listens-for-child-event
(部分)答案是这样的:
覆盖类具有自己的模板实例,因此必须将基本模板链接到它
细节:https://github.com/angular/angular/issues/18920
所以在基类中添加组件anotations:
并且子类必须具有引用它的模板
现在我不知道如何从typescript子组件调用该函数来适应上面的问题
如果有人能回答,我会更新这个答案
谢谢
我的工作方式是删除exportas
在代码中
...