为什么 Angular 基础组件 html 元素无法识别数据更改?

问题描述 投票:0回答:1

我在这里缺少什么?这是创建 Angular 18 基础组件和扩展它的继承组件的简化示例。两者都是独立的。一切看起来都很好,因为继承组件可以看到其中的基本组件属性和方法。基本方法和属性需要重写。在基础或继承中完成的变量更改都会显示出来。我的问题是 base 中的 html 似乎无法识别变量中的任何更改。更改基本或继承中的变量,继承 html 会做出响应。不是我所期望的。

我创建一个基本组件 QueryBaseComponent

name:string='nancy;

changeName(newName:string){
    this.name = newName;
    console.log(this.name);//shows liberace
}

onClick(event:any){
//always fires even if it is override in heir component
    console.log('base');
}

html

<label>{{name}}</label>  //always shows initial value of nancy, doesn't change
<button (click)="onClick($event)">hit me</button>
<ng-content select="[position=bottom]"></ng-content>

i extend the base component

export class QueryTextComponent extends QueryBaseComponent implements AfterViewInit

ngAfterViewInit(){
    this.changeName('liberace');
}

override onClick(event:any){
//never gets hit
    console.log('heir');
}

html

<app-query-base>
    <div position="bottom">
        <label>{{name}}</label> //shows nancy and then liberace
    </div>
</app-query-base>
    
 
html angular inheritance components extend
1个回答
0
投票

ngAfterViewInit
这样的事件钩子在继承组件类时不会被继承,你必须手动调用它们,这很好,因为你希望在事件钩子中有任何自动触发功能。

您必须致电家长

ngAfterViewInit
super.ngAfterViewInit()

ngAfterViewInit(){
    super.ngAfterViewInit();
}
© www.soinside.com 2019 - 2024. All rights reserved.