Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

angular - Inherited component fails to update property in base component

I have an Angular component inheriting a base component.

@Component({
selector: "my-baseclass-component",

template: `
  <div style="border:1px solid red;padding:10px">
   counter value (check console to see it gets incremented) : {{ counter }}
  <ng-content select="[body]"></ng-content>
  <br />
</div>
`
 })
 export class BaseClassComponent {
 public counter = 0;
 constructor() {}
 }

I just want to increment a counter in the base component from the inherited component when clicking on a button.

@Component({
selector: 'my-inherited-component',
template: `<my-baseclass-component #myBaseclass>
 <div style="border:1px solid black" body>Inherited Component Content
<button (click)="click()">toggle</button>
 </div>
  </my-baseclass-component>`
})
 export class InheritedComponent extends BaseClassComponent {  

  click(){
    this.counter++;
    console.log('clicked:' + this.counter);
  }
}

The counter variable is displayed in the base component template using the curly brackets notation {{counter}} but it is never refreshed although the value itself is incremented correctly.

I have reproduced the issue in a stackblitz :

https://stackblitz.com/edit/angular-ivy-sssxvt?file=src/app/baseclass.component.ts

What am I doing wrong ?

question from:https://stackoverflow.com/questions/66054742/inherited-component-fails-to-update-property-in-base-component

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you put <app-some-comp></app-some-comp> in template you tell Angular to instantiate a new isolated instance of AppSomeComponent.

In your example

@Component({
  ...
  template: `
       <my-baseclass-component #myBaseclass>
           ....
      </my-baseclass-component>`
})
export class InheritedComponent extends BaseClassComponent {}

you created InheritedComponent component(which is derived from BaseClassComponent class) and a new separated instance of <my-baseclass-component.

If you want the counter to be reflected in inner <my-baseclass-component component you should update it itself.

There are several options:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...