如果我有:
@Component({
selector: 'app1',
templateUrl: './app1.html',
})
export class A implement OnInit {
ngOnInit() {
}
}
@Component({
selector: 'app2',
templateUrl: './app2.html',
})
export class B implement OnInit {
ngOnInit() {
}
}
那么我如何从 A 类调用 B 类的ngOnInit()
并且我的类 B 模板应该更新(渲染)?
好的 所以这是@ViewChild()解决方案。ViewChild 允许您从父组件控制子组件。假设你有MyMain.component.ts和MyChild.component.ts(名称为"MyChildComponent")。
在父项中,创建一个变量:ViewChild(MyChildComponent) childComponent:MyChildComponent。现在,您可以访问子函数和变量。
在父级中创建函数
refreshChild(data) { this.childComponent.refreshFromParent(data); }
另一个在你的孩子
refreshFromParent(data) { this.data = data ... }
为此,您必须使组件 B 可注射。 我们为此使用 @Injectable(),并在其中使用 Provider,如 'root' 所示。
组件 A
@Component({
selector: 'app1',
templateUrl: './app1.html',
})
export class A implement OnInit {
constructor( private a: A ){}
ngOnInit() {
this.a.ngOnInit();
}
}
构成部分B
@Component({
selector: 'app2',
templateUrl: './app2.html',
})
@Injectable({
providedIn: 'root',
})
export class B implement OnInit {
ngOnInit() {
}
}
这对我有用,请让我知道这是否有效