ngfor当新数据发送到类型数组的变量时不会更新
我正在尝试通过NGFOR进行页面更新数据,但这是不可能的。 我有两个组件app.component和第二组件。
在app.com.ponent中,有一个按钮,当按下时会在第二组件中激活Change()函数。此功能更新数组类型变量。当数组更新而不是DOM时出现问题。
app.component.ts
export class AppComponent {
data: string = 'A1';
constructor(private second: SecondComponent) {}
send() {
this.second.change(this.data);
}
}
app.component.html
<p>APP COMPONENT</p>
<button class="button" (click)="send()">Push</button>
<secondComponent-app></secondComponent-app>
secondcomponent.ts
export class SecondComponent {
box1: any = ['car', 'plane'];
change(data) {
if (data == 'A1') {
this.box1 = ['car1', 'plane1'];
}
console.log(this.box1);
}
}
secondcomponent.html
<p>SECOND COMPONENT</p>
<div *ngFor="let item of box1 ">{{item}}</div>
有人可以帮助我吗?提前致谢。 请参阅Stackblitz https://angular-ivar-ivy-qbeqzo.stackblitz.io/
I am trying to make the page update data through ngFor but it is impossible.
I have two components app.component and secondComponent.
In the app.component there is a button that when pressed activates the change() function in the secondComponent. This function updates an array type variable. The problem arises when the array is updated but not the DOM.
app.component.ts
export class AppComponent {
data: string = 'A1';
constructor(private second: SecondComponent) {}
send() {
this.second.change(this.data);
}
}
app.component.html
<p>APP COMPONENT</p>
<button class="button" (click)="send()">Push</button>
<secondComponent-app></secondComponent-app>
secondComponent.ts
export class SecondComponent {
box1: any = ['car', 'plane'];
change(data) {
if (data == 'A1') {
this.box1 = ['car1', 'plane1'];
}
console.log(this.box1);
}
}
secondComponent.html
<p>SECOND COMPONENT</p>
<div *ngFor="let item of box1 ">{{item}}</div>
Can anybody help me?. Thanks in advance.
See StackBlitz https://angular-ivy-qbeqzo.stackblitz.io/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的父组件的构造函数中,Angular注入了您的
secondomponent
(似乎)的实例,该实例与组件模板中一个由&lt; second; secondComponent-app&gt; <<<
>&lt; <<<<<< /code>
而不是将其放入构造函数中,而是执行以下操作:
##
表示),例如@ViewChild
可以访问父母类主体中模板中的组件:然后,您应该能够将
secondcomponent
作为字段处理你父母的。更多信息: https://angular.io/api/core/core/core/viewchild
In your parent component's constructor, Angular is injecting an instance of your
SecondComponent
(it would seem) that is a different instance than the one in your component's template specified by<secondComponent-app>
Instead of putting it into the constructor, do the following:
#
), e.g.<secondComponent-app #second>
@ViewChild
to gain access to the component in the template in your parent's class body like so:You should then be able to handle the
SecondComponent
as a field of your parent.More info: https://angular.io/api/core/ViewChild