首页 > 解决方案 > 当我从属性添加对象时,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>

标签: angularangular-elements

解决方案


根据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
    }
}

推荐阅读