我有Angular Element Component(带有Angular 8),它有2个道具。当我尝试将某些内容推送到数组中时,Shadow-Root不会重新渲染它(而是改为计数器)。当我在组件中推动对象时如何强制渲染?
谢谢
这是Component类
export class CounterComponent implements OnInit {
@Input()
counter: number;
@Input()
images: Array<any>;
constructor(private cdr: ChangeDetectorRef) { }
ngOnInit() {
this.counter = 0;
this.images = [];
}
add() {
this.counter++;
}
reduce() {
this.counter--;
}
@Input()
addImage() {
this.images.push({ ciccio: 'piccio'}); //no rerender
this.cdr.detectChanges(); // Error cdr is null
}
}
AppModule
import { BrowserModule, platformBrowser } from '@angular/platform-browser';
import { NgModule, Injector } from '@angular/core';
import { CounterComponent } from './counter/counter.component';
import { createCustomElement } from '@angular/elements';
@NgModule({
declarations: [
CounterComponent
],
imports: [
BrowserModule
],
providers: [],
entryComponents: [CounterComponent]
})
export class AppModule {
constructor(private injector: Injector) {
}
ngDoBootstrap( ) {
const el = createCustomElement(CounterComponent, {injector: this.injector});
customElements.define('count-component', el);
}
}
这是组件模板
<div style="display: flex;justify-content: center;flex-direction: column">
<h1>Counter component</h1>
<h4>Count ---> {{counter}}</h4>
<button (click)="add()">Increase</button>
<button (click)="reduce()">Decrease</button>
</div>
<h3>
Images {{images.length}}
</h3>
答案 0 :(得分:0)
@Input()
addImage() {
this.ngZone.run(() => {
this.images.push({ ciccio: 'piccio'}); //no rerender
});
}
您可以尝试从@ angular / core注入NgZone并在其中运行吗?
答案 1 :(得分:0)
根据Angular文档中的"Angular Elements Overview":
我们正在研究可在其他框架上构建的Web应用程序使用的自定义元素。最小,独立的Angular框架版本将作为一项服务注入,以支持组件的更改检测和数据绑定功能。有关开发方向的更多信息,请查看此video presentation。
如8:28 in the video presentation attached above中所述,依赖注入适用于Angular Elements中的自定义元素。因此,将ChangeDetectorRef
注入到您的自定义元素中,并在使detectChanges()
数组发生突变时调用images
,就像这样:
export class CounterComponent /* ... */ {
constructor(private cdr: ChangeDetectorRef) { }
/* ... */
addImage() {
this.images.push({ ciccio: 'piccio'});
this.cdr.detectChanges(); // change detection will detect the change in `images` and render
}
}
答案 2 :(得分:0)
尝试一下,这实际上将更改组件上的images属性的值,使它可以看到更改:
@Input()
addImage() {
this.images = [...this.images, { ciccio: 'piccio'}]; // should render
}
随随便便:here