我有一个父组件和一个子组件。在子组件中有一个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中-
import {ChildComponent} from './child-component';
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)访问父组件。
答案 0 :(得分:0)
在ngAfterViewInit
中切换布尔值后,我会尝试手动运行更改检测。
这是它的外观。
import { ChangeDetectorRef } from '@angular/core';
import {ChildComponent} from './child-component';
export class ParentComponent {
loadcondition : boolean = true;
@ViewChild(ChildComponent) private childreference: ChildComponent;
constructor(private ref: ChangeDetectorRef) {}
ngAfterViewInit() {
this.loadcondition = this.childreference.opened= false;
this.ref.detectChanges();
console.log('on after view init', this.childreference);
}
}