首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将对象从父对象传递给子对象

将对象从父对象传递给子对象
EN

Stack Overflow用户
提问于 2018-04-08 11:24:38
回答 3查看 1.7K关注 0票数 0

我有一个约定对象,必须作为子组件的输入传递,当我在子模板中调用它时,会显示约定id,但当我试图在console.log中使用约定时,会出现未定义的情况。我尝试将我的console.log放在子构造函数以及ngOnInit、ngAfterViewInit和ngOnChanges中。对于ngOnChanges,当我只将约定的id作为子组件的输入传递时,它工作得很好,但是我需要传递约定而不是它的id。

index.component.ts

代码语言:javascript
复制
@Component({
    templateUrl: './index.template.html',
    selector: 'be-convention-update',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ConventionUpdateComponent {

    private convention$: Convention;
    private conventionId: number;

    constructor(private route: ActivatedRoute,
        private conventionService: ConventionService) {
        this.route.params.subscribe(
            (params: any) => {
                this.conventionId = params['id'];
                this.conventionService.getOne(this.conventionId).subscribe(response => this.convention$ = response);
            }
        );
    }

}

index.template.html

代码语言:javascript
复制
<be-form-convention [convention]="convention$"></be-form-convention>

form.component.ts

代码语言:javascript
复制
@Component({
    selector: 'be-form-convention',
    templateUrl: './form.template.html',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ConventionFormComponent implements OnChanges, OnInit {

    @Input() convention: Convention;

    constructor() {
    }

    public ngAfterViewInit() {
      console.log(this.convention); //undefined
    }

    public ngOnInit(): void {
      console.log(this.convention); //undefined
    }

    public ngOnChanges(changes: SimpleChanges): void {
      const object: SimpleChange = changes.convention;
      console.log('prev value: ', object.previousValue); //undefined
      console.log('got name: ', object.currentValue); //undefined
    }

}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-04-08 11:42:48

根据我的理解,当您接收到输入或输入值更改时,您希望做一些操作。

可以在set函数中使用输入指令,如下所示:

代码语言:javascript
复制
_convention: Convention;
@Input()
set convention(convention: Convention) {
    this._convention = convention;
    //the code you want to handle after input is received
}
票数 1
EN

Stack Overflow用户

发布于 2018-04-08 14:34:56

由于这是一个异步操作,我建议您等到约定获得值时再使用*ngIf加载子组件,而约定对象不是空的。

代码语言:javascript
复制
<ng-container *ngIf="convention$">
<be-form-convention [convention]="convention$"></be-form-convention>
</ng-container>
票数 1
EN

Stack Overflow用户

发布于 2018-04-08 12:18:38

对于组件-组件通信,我总是使用服务。

我所做的是:创建一个服务并创建两个函数(getData和setData)。

每当我想将一些数据从一个组件发送到另一个组件时,我就调用setData方法,当我想在其他组件中接收数据时,我使用getData方法。

下面是一个示例:

从“@角/核心”导入{ Injectable };

代码语言:javascript
复制
@Injectable()
export class DataExchange {

  data; //Global Variable of 'any' type.

  setData(data){
this.data = data;
  }

getData():any{
  return this.data;
}
}
票数 -3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49717314

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档