为什么@Input角传递作为数组更新外面没有发送Emit使用EventEmitter?



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

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);
}
}

复制示例

你正在通过Input传递一个数组给子组件,因为它是一个非原语值,所以子组件将接收到父组件中定义的数组的引用。因此,我们可以从任何地方改变数组。

这个行为与Angular无关,因为它是Javascript的基础。

最新更新