如何解决使用ViewChild更新ChildComponent属性
我是相当新的Angular,并且正在玩ViewChild和ViewChildren。我尝试了一种情况
我的today = new Date()
中有一个Component2
属性。而且我正在使用Component1
在ViewChild
中访问此属性,并使用setInterval() for every second
更新时间。
现在,我使用*ngFor
指令创建了多个Component2。但是我看到只有初始Component2的today
属性正在更新。剩余的未更新。
下面是我的代码。
Component1.ts
import{Component,ViewChild,ElementRef,AfterViewInit,OnInit,ViewChildren,QueryList}from"@angular/core";
import { Component2 } from "./Component2";
@Component({
selector: "comp1",templateUrl: "./Component1.html"
})
export class Component1 implements AfterViewInit {
@ViewChild(Component2) myComponent2: Component2;
public Component2Array: Array<String> = [
"Paragraph one","Paragraph Two","Paragraph Three","Paragraph Four"
];
ngAfterViewInit(): void {
console.log("Component 1 => AfterViewInit",this.myComponent2);
setInterval(()=>
{
this.myComponent2.today = new Date();
})
}
}
Component1.html
<div #div1>
<h1 #header1>This is Header 1</h1>
</div>
<div #component2Div>
<comp2 *ngFor="let item of Component2Array" [message]="item"> </comp2>
</div>
Component2.ts
import {
Component,Input
} from "@angular/core";
@Component({
selector: "comp2",templateUrl: "./Component2.html"
})
export class Component2 implements AfterViewInit {
public today = new Date();
@input() message: string;
ngAfterViewInit(): void {}
}
Component2.html
<div>
<h1>This is Component 2</h1>
<h2>{{today}}</h2>
<div>
{{message}}
<div></div>
</div>
</div>
任何人都可以让我知道为什么仅初始Component2的today
属性正在更新。
Example here
预先感谢
解决方法
我自己解决了此问题。我使用的是ViewChild
而不是ViewChildren
。
更改了代码
@ViewChild(Component2) myComponent2: Component2;
到
@ViewChildren(Component2) myComponent2: QueryList<Component2>;
和
来自
setInterval(()=>
{
this.myComponent2.today = new Date();
})
到
setInterval(() => {
this.components.forEach((element) => (element.today = new Date()));
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。