【发布时间】:2019-05-05 13:15:38
【问题描述】:
我想从父组件设置子组件属性
parent.component.html
<div>
<child-detail #myCarousel [childList]="detail.List" ></child-detail>
</div>
parent.component.ts
@Component({
selector: "parent",
templateUrl: "./parent.component.html",
})
export class AppComponent {
public detail; // it is of JSON type
}
child.component.ts
@component({
selector:'child-detail',
templateUrl: './child.component.html'
})
export class ChildDetailComponent{
@Input() public childList; // that list of array type
}
child.component.html
<div *ngFor = "let list of childList">
<li>{{list}} </li>
</div>
我知道我可以通过@Input() 绑定设置此属性,但这只会在组件初始化时设置,我想在某个时候以编程方式在中间设置它。
我知道我可以使用
访问父级中的这个子属性@ViewChild(ChildDetailComponent) childDetailComponent: ChildDetailComponent;
console.log(this.childDetailComponent.childList);
但我想在任何父母事件中以编程方式设置它。
【问题讨论】:
-
那么为什么不能使用
input属性并在父事件上填充该输入属性? -
*但这只会在组件初始化时设置 *??这不是真的。每当您更改父项中的道具时,都会设置它。阅读
ngOnChanges()钩子 -
@xyz 你能详细说明一下吗?
-
当父组件中
childList的值发生变化时,childComponent中的childList的值也将被更新,但是如果你去更改父组件中childList的值childList的值在子组件中发生变化,您可以对childList使用set 方法Input -
只是一个注释。您正在使用 TypeScript。 TypeScript 有类型。那么为什么不使用
// that list of array type,而是正确声明变量的类型呢?
标签: angular