为什么作为数组传递的@Input angular 会在外部更新而不使用 EventEmitter 发送 Emit?

我不明白为什么 Angular 在不使用 @Output EventEmitter 的情况下更新组件内部修改的一个属性 this.list,我注意到只有在我传递数组时才会发生这种情况。

import { Component,OnInit } from "@angular/core";
import { Item } from "./models/item";

@Component({
  selector: "app-root",templateUrl: "./app.component.html",styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  title = "Hello";
  list: Item[];

  constructor() {
    this.list = [
      {
        text: "Link 1"
      },{
        text: "Link 2"
      }
    ];

    setTimeout(() => {
      console.log("Itens",this.list);
    },11500);
  }

  ngOnInit() {}
}

注意我没有使用双向绑定 [()]

<menu [items]="list"></menu>

组件:

import { Component,Input } from "@angular/core";
import { Item } from "../../models/item";

@Component({
  selector: "menu",styleUrls: ["./menu.component.css"],templateUrl: "./menu.component.html"
})
export class MenuComponent {
  @Input() items: Item[];

  constructor() {
    // after 10 seconds change the data
    setTimeout(() => {
      this.items.push({
        text: "Link 3"
      });
    },5000);
  }
}

Reproduce example

ingkao84 回答:为什么作为数组传递的@Input angular 会在外部更新而不使用 EventEmitter 发送 Emit?

您通过 Input 将数组传递给子组件,因为它是非 primitive 值,子组件将收到对父组件中定义的数组的引用。因此我们可以从任何地方改变数组。

该行为与 Angular 无关,因为它是 Javascript 基础。

本文链接:https://www.f2er.com/380.html

大家都在问