我有一个应用程序,其中验证需要引用应用程序控制器。我的App控制器如下所示:
export class AppComponent {
objectName: ObjectName;
constructor(public dialog: MatDialog) {
this.objectName= new ObjectName();
this.objectName.objects1 = this.getObjects1();
this.objectName.objects2 = this.getObjects2();
}
从孩子的组件访问此数据的最佳方法是什么?
答案 0 :(得分:0)
如果它是直接子级,则只需使用Input参数即可。如果是孙子或兄弟姐妹,则最佳做法是使用共享服务并进行交流,而不是BehaviorSubject。
Read this, it is te official guide and will answer all your questions
答案 1 :(得分:0)
如果要在父组件中访问以下任何内容,请使用Angular的@ViewChild
装饰器。
获取价值我们需要执行以下任务:
答案 2 :(得分:0)
I'm used to do that with an EventEmitter
as follow :
emitter.helper.ts
// Angular modules
import { Injectable } from '@angular/core';
import { EventEmitter } from '@angular/core';
// Models
import { ObjectName } from '...';
@Injectable()
export class EmitterHelper
{
public static emitObjectName : EventEmitter<ObjectName> = new EventEmitter();
public static sendObjectName(objectName : ObjectName) : void
{
this.emitObjectName.emit(objectName);
}
}
Don't forget to share this helper by adding it to the providers
of app.module.ts
.
Now you can import and use the EmitterHelper
between components :
Component A
EmitterHelper.sendObjectName(this.objectName);
Component B
EmitterHelper.emitObjectName.subscribe((objectName : ObjectName) =>
{
console.log(objectName);
});