angular - 当我从属性添加对象时,Angular Element 组件不会更新
问题描述
我有 Angular 元素组件(使用 Angular 8),它有 2 个道具。当我尝试在数组中推送某些东西时,Shadow-Root 不会重新渲染它(而是计数器)。当我在组件中推送对象时如何强制渲染?
谢谢
这是组件类
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
}
}
应用模块
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>
解决方案
根据Angular 文档中的“Angular Elements Overview” :
我们正在开发可被基于其他框架构建的 Web 应用程序使用的自定义元素。Angular 框架的最小、自包含版本将作为服务注入,以支持组件的更改检测和数据绑定功能。有关发展方向的更多信息,请查看此视频演示。
正如上面附加的视频演示中的 8:28 所述,依赖注入适用于 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
}
}
推荐阅读
- database - 目标表在开始运行 Kettle 脚本时被截断
- c# - 如何在c#中获取存储过程输出参数
- php - 从 Woocommerce 3.3 中的 Storefront 主题中删除面包屑
- php - 试图在php数组中获取非对象的属性
- javascript - 如何用javascript删除这种情况?
- php - RelationNotFoundException 调用模型 [App\User] 上的未定义关系 [userStories]
- javascript - 需要澄清使用js创建动态html表
- amazon-web-services - AWS ElastiCache redis 操作耗时超过 10 毫秒
- sql - 我如何格式化这样的列?
- mongodb - 如何在 MongoDB 的对象中查找特定数组?