【发布时间】:2019-10-10 23:10:13
【问题描述】:
我有一个父组件和一个子组件。子组件中有一个 ngif 语句。我想在父组件中使用相同的 ngif。 下面是示例代码。
子组件:
`selector: 'child-component',
template: `
<div class="container">
<div class="panel panel-danger">
<div
class="panel-heading"
(click)="opened = !opened">
Click me
</div>
<div
class="panel-body"
*ngIf="opened">body</div>
</div>
</div>
`,
styleUrls: [ './app.component.css' ]
})
export class ChildComponent {
opened = false;
title = 'Hello Panel';
body = 'this is the content';
}
`
parent component:
<h3 *ngIf="loadcondition">This is Prent component</h3>
我尝试使用@Viewchild 实现相同的目的。 在 parent.component.ts--
从'./child-component'导入{ChildComponent};
loadcondition : boolean = true;
@ViewChild(ChildComponent) private childreference: ChildComponent;
ngAfterViewInit() {
this.loadcondition = this.childreference.opened= false;
console.log('on after view init', this.childreference);
}
parent.component.html--
<div class="center"><h3 *ngIf="loadcondition">This is Parent component</h3>
<child-component></child-component>
</div>
但不幸的是,子引用在控制台中返回 undefined。有没有其他方法可以将子条件访问到父组件而不是@Viewchild。
【问题讨论】:
-
在子组件中使用
@Input() opened = false作为定义 -
如果父子条件相同,则只需要父子条件。
-
@Ronald Haan....我试过但仍然得到相同的响应...childreference return undefined
-
@trichetriche...能否请您详细说明一下,因为在这种情况下,条件基于子组件数据
标签: angular